﻿//Begin Classes

function MapWindows() {

    var oWnd;
    var page;

    this.setMapWindows = function (oWnd, page)
    {
        this.oWnd = oWnd;
        this.page = page;
    }
}

function GeoFence() {

    var geoFenceID = "";
    var name = "";
    var polygono;

    this.numPosList = [];
    this.latitudeList = [];
    this.longitudeList = [];

    this.checked = false;

    this.showGeoFence = function (opener) {
        this.polygono = opener.objMapControl.createPolygono(this.polygono, this.numPosList, this.latitudeList, this.longitudeList);
    };

    this.hideGeoFence = function (opener) {
        opener.objMapControl.clearPolygono(this.polygono);
    };

    this.setGeoFence = function (geoFenceID, name, numPosList, latitudeList, longitudeList) {

        this.geoFenceID = geoFenceID;
        this.name = name;

        this.numPosList = numPosList;
        this.latitudeList = latitudeList;
        this.longitudeList = longitudeList;

    };

    this.updateGeoFence = function (pgeoFenceID, pname, pnumPosList, platitudeList, plongitudeList) {

        this.geoFenceID = pgeoFenceID;
        this.name = pname;
        this.numPosList = pnumPosList;
        this.latitudeList = platitudeList;
        this.longitudeList = plongitudeList;
    };
}

function GPSStock() {

    var index;
    var gpsImei;
    var name;
    var lastAction;
    var currentAction;

    var image;
    var position;
    var address;

    this.setGPSStock = function (index, gpsImei, name, lastAction, currentAction) {
        this.index = index;
        this.gpsImei = gpsImei;
        this.name = name;
        this.lastAction = lastAction;
        this.currentAction = currentAction;
    }

    this.setGPSImei = function (objMapControl, gpsImei, name, image, latitude, longitude) {
        this.gpsImei = gpsImei;
        this.name = name;
        this.position = objMapControl.addPosition(stringToFloatForPosition(latitude), stringToFloatForPosition(longitude));
        this.image = objMapControl.addImage(image);
        this.address = this.position.lat() + "," + this.position.lng();
    }
}

function GPSGroup() {
    var gpsGroupID;
    var name;

    this.setGPSGroup = function(gpsGroupID, name){
        this.gpsGroupID = gpsGroupID;
        this.name = name;
    }
}

function ClientsControl() {
    var username;
    var name;
    var gpsImei;
    var gpsName;
    var date;
    var timeBegin;
    var timeEnd;
    var status;
    var progress;
    var lastExecution;
    var clientGroupID;
    var clientGroupName;
    var latOrigin;
    var lngOrigin;

    this.setClientsControl = function (username, name, gpsImei, gpsName, date, timeBegin, timeEnd, status, progress, lastExecution, clientGroupID, clientGroupName, latOrigin, lngOrigin) {
        this.username = username;
        this.name = name;
        this.gpsImei = gpsImei;
        this.gpsName = gpsName;
        this.date = date;
        this.timeBegin = timeBegin;
        this.timeEnd = timeEnd;
        this.status = status;
        this.progress = progress;
        this.lastExecution = lastExecution;
        this.clientGroupID = clientGroupID;
        this.clientGroupName = clientGroupName;
        this.latOrigin = latOrigin;
        this.lngOrigin = lngOrigin;
    }
}

function ClientGroup() {
    var clientGroupID;
    var name;
    var checked;

    this.setClientGroup = function (clientGroupID, name) {
        this.clientGroupID = clientGroupID;
        this.name = name;
        this.checked = false;
    }
}

function BusRoute() {
    var busRouteID;
    var name;
    var checked;

    this.setBusRoute = function (busRouteID, name) {
        this.busRouteID = busRouteID;
        this.name = name;
        this.checked = false;
    }
}

function VPCProcess()
{
    var numControl;
    var numCard;
    var driverID;
    var driverName;
    var gpsImei
    var gpsImeiName;
    var busRouteID;
    var busRouteName;
    var date;
    var timeBegin;
    var timeEnd;
    var status;
    var progress;
    var lastExecution;

    this.setVPCControl = function (numControl, numCard, driverID, driverName, gpsImei, gpsImeiName, busRouteID, busRouteName, date, timeBegin, timeEnd, status, progress, lastExecution){
        this.numControl = numControl;
        this.numCard = numCard;
        this.driverID = driverID;
        this.driverName = driverName;
        this.gpsImei = gpsImei;
        this.gpsImeiName = gpsImeiName;
        this.busRouteID =busRouteID;
        this.busRouteName = busRouteName;
        this.date = date;
        this.timeBegin = timeBegin;
        this.timeEnd = timeEnd;
        this.status = status;
        this.progress = progress;
        this.lastExecution = lastExecution;
    }
}

function Company() {
    var companyID;
    var name;
    var checked;

    this.setCompany = function (companyID, name) {
        this.companyID = companyID;
        this.name = name;
        this.checked = false;
    }
}

function ClientsToVisit() {
    var numPos;
    var clientID;
    var clientName;
    var arriveDateTime;
    var dateTimeEnd;
    var distanceKmTravel;
    var distanceKmTravelText;
    var latitude;
    var longitude;
    var hoursTravel;
    var minutesTravel;
    var timeOnTravelText;
    var hours;
    var minutes;
    var timeOnClientText;
    var marker;
    var infoWindow;
    var position;

    this.setClientsToVisit = function (objMapControl, numPos, clientID, clientName, arriveDateTime, dateTimeEnd, distanceKmTravel, latitude, longitude, hoursTravel, minutesTravel, hours, minutes)
    {
        this.numPos = numPos;
        this.clientID = clientID;
        this.clientName = clientName;
        this.arriveDateTime = arriveDateTime;
        this.dateTimeEnd = dateTimeEnd;
        this.distanceKmTravel = distanceKmTravel;
        this.latitude = latitude;
        this.longitude = longitude;
        this.hoursTravel = hoursTravel;
        this.minutesTravel = minutesTravel;
        this.hours = hours;
        this.minutes = minutes;

        this.distanceKmTravelText = this.distanceKmTravel + " km";
        
        if(this.hoursTravel > 0){
            this.timeOnTravelText = this.hoursTravel + " h ";
        }
        this.timeOnTravelText += this.timeOnTravelText + this.minutesTravel + " min";

        this.distanceKmTravelText = this.distanceKmTravel + " km";
        
        if(this.hours > 0){
            this.timeOnClientText = this.hours + " h ";
        }
        this.timeOnClientText += this.timeOnClientText + this.minutes + " min";

        this.marker = objMapControl.addMarker(images.locationClient, objMapControl.addPosition(latitude, longitude), clientName);
        //infowindows

        this.position = objMapControl.addPosition(stringToFloatForPosition(this.latitude), stringToFloatForPosition(this.longitude));
    }
}

function Client() {
    var clientID;
    var clientName;
    var marker;
    var checked;
    var visible;
    var clientGroupID;
    var clientGroupName;
    var numPos;
    var position;
    var address;
    var kms;
    var kmsText;
    var duration;
    var durationText;
    var infoWindow;

    this.setClient = function (objMapControl, clientID, clientName, latitude, longitude) {
        this.clientID = clientID;
        this.clientName = clientName;

        this.marker = objMapControl.addMarker(images.locationClient, objMapControl.addPosition(latitude, longitude), clientName);                
        this.marker.setVisible(false);

        this.position = objMapControl.addPosition(stringToFloatForPosition(latitude), stringToFloatForPosition(longitude));
        this.address = this.position.lat() + "," + this.position.lng();
        this.checked = false;
        this.visible = false;
        this.numPos = null;
        this.kms = null;
        this.kmsText = null;
        this.duration = null;
        this.durationText = null;
    }

    this.setClientGroup = function (clientGroupID, clientGroupName) {
        this.clientGroupID = clientGroupID;
        this.clientGroupName = clientGroupName;
    }
}

function BusStop() {
    var busStopID;
    var name;
    var marker;
    var checked;

    this.setBusStop = function (objMapControl, busStopID, name, latitude, longitude) {
        this.busStopID = busStopID;
        this.name = name;

        this.marker = objMapControl.addMarker(images.locationBusStop, objMapControl.addPosition(latitude, longitude), name);
        this.marker.setVisible(false);

        this.checked = false;
    }
}

function StopMarker() {
    var stopMarker;
    var infoWindow;
    var initialTimeStop;
    var finalTimeStop;

    this.setStopMarker = function (stopMarker, infoWindow, initialTimeStop) {
        this.stopMarker = stopMarker;
        this.infoWindow = infoWindow;
        this.initialTimeStop = initialTimeStop;
    }
}

function PeopleCounterMarker() {
    var peopleCounterMarker;
    var infoWindow;
    var peopleIn;
    var peopleOut;
    var peopleTotalInside
    var peopleTotalIn;
    var peopleTotalOut;

    this.setPeopleCounterMarker = function (peopleCounterMarker, infoWindow, peopleIn, peopleOut, peopleTotalInside, peopleTotalIn, peopleTotalOut) {
        this.peopleCounterMarker = peopleCounterMarker;
        this.infoWindow = infoWindow;
        this.peopleIn = peopleIn;
        this.peopleOut = peopleOut;
        this.peopleTotalInside = peopleTotalInside;
        this.peopleTotalIn = peopleTotalIn;
        this.peopleTotalOut = peopleTotalOut;
    }
}

function User() {

    var username;
    var name;
    var firstName;
    var lastName;

    this.setUser = function (username, name, firstName, lastName) {
        this.username = username;
        this.name = name;
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

function UserGroup(){
    var userGroupID;
    var name;

    this.setUserGroup = function (userGroupID, name)
    {
        this.userGroupID = userGroupID;
        this.name = name;
    }
}

function Department() {
    var departmentID;
    var name;

    this.setDepartment = function (departmentID, name) {
        this.departmentID = departmentID;
        this.name = name;
    }
}

function TrackData() {

    var imei;
    var hour;
    var speed;
    var position;
    var image;
    var tipoVehiculo;
    var marker;
    var currentKm;

    var peopleIn;
    var peopleOut;
    var peopleTotalInside;
    var peopleTotalIn;
    var peopleTotalOut;

    var totalTrack;
    var distanceKm;
    var totalKm;

    this.setTrackData = function (objMapControl, pimei, pspeed, platitude, plongitude, pimageLocation, phour, peopleIn, peopleOut, peopleTotalInside, peopleTotalIn, peopleTotalOut) {
        this.imei = pimei;
        this.hour = phour;
        this.speed = pspeed;
        this.position = objMapControl.addPosition(stringToFloatForPosition(platitude), stringToFloatForPosition(plongitude));
        this.image = objMapControl.addImage(pimageLocation);

        this.peopleIn = peopleIn;
        this.peopleOut = peopleOut;
        this.peopleTotalInside = peopleTotalInside;
        this.peopleTotalIn = peopleTotalIn;
        this.peopleTotalOut = peopleTotalOut;
    };

    this.setAditionalInfo = function (totalTrack, distanceKm, totalKm)
    {
        this.totalTrack = totalTrack;
        this.distanceKm = distanceKm;
        this.totalKm = totalKm;
    }
}

function TrackDataLastLocationImei() {

    var imei;
    var imeiName;
    var imeiDescription;
    var imeiSimNumber;
    var imeiTypeID;
    var imeiTypeIDDescription;
    var gpsModelID;
    var gpsModelIDName;
    var image;
    var gpsGroupID
    var groupName;

    var lastMessageImei;

    var peopleIn;
    var peopleOut
    var peopleInside;

    var position;
    var marker;
    var speed = 0;
    var heading = 0;
    var geoferenceExitAlarm = null;
    var geoferenceEnterAlarm = null;
    var sosAlarm = null;

    var notificationTextList = [];

    this.setInfo = function (objMapControl, gpsGroupID, pimei, pimeiName, groupName, pimeiDescription, pimeiSimNumber, pimeiTypeID, pimeiTypeIDDescription, platitude, plongitude, pimage, plastMessageImei, peopleIn, peopleOut, peopleInside) {

        this.gpsGroupID = gpsGroupID;
        this.imei = pimei;
        this.imeiName = pimeiName;
        this.groupName = groupName;
        this.imeiDescription = pimeiDescription.replace(/^\s*|\s*$/g, "");
        this.imeiSimNumber = pimeiSimNumber;
        this.imeiTypeID = pimeiTypeID;
        this.imeiTypeIDDescription = pimeiTypeIDDescription;
        var latitude = parseFloat(platitude.toString().replace(",", "."));
        var longitude = parseFloat(plongitude.toString().replace(",", "."));
        this.image = objMapControl.addImage(pimage);//new google.maps.MarkerImage(images.location + pimage);

        this.position = objMapControl.addPosition(latitude, longitude);//new google.maps.LatLng(latitude, longitude);
        this.marker = objMapControl.addMarker(this.image, null, this.imeiDescription);

        this.lastMessageImei = plastMessageImei;
        this.notificationTextList = [];

        this.peopleIn = peopleIn;
        this.peopleOut = peopleOut;
        this.peopleInside = peopleInside;
    };

    

    //Se llaman directamente las sentencias de Google Map, si se invocan las opciones de objMapControl, el paso del parámetro pierde la variable de mapas o de longitudes.
    this.setMinInfo = function (objMapControl, pimei, pimeiName, pimeiDescription, platitude, plongitude, pimage, pmap) {

        this.imei = pimei;
        this.imeiName = pimeiName;
        this.imeiDescription = pimeiDescription.replace(/^\s*|\s*$/g, "");
        var latitude = parseFloat(platitude.toString().replace(",", "."));
        var longitude = parseFloat(plongitude.toString().replace(",", "."));
        this.image = objMapControl.addImage(pimage);//new google.maps.MarkerImage(images.location + pimage);

        this.position = new google.maps.LatLng(latitude, longitude); //objMapControl.addPosition(latitude, longitude);//new google.maps.LatLng(latitude, longitude);
        this.marker = new google.maps.Marker({ map: pmap, icon: this.image, position: this.position, title: this.imeiDescription});//objMapControl.addMarkerWithMap(this.image, this.position, this.imeiDescription, pmap);
    };

    this.updatePosition = function (imeiSelected, objMapControl, latitude, longitude, speed, heading, lastMessageImei, peopleIn, peopleOut, peopleInside) {
        var latitude = parseFloat(latitude.toString().replace(",", "."));
        var longitude = parseFloat(longitude.toString().replace(",", "."));

        this.lastMessageImei = lastMessageImei;

        this.position = objMapControl.addPosition(latitude, longitude);
        
        if (imeiSelected == this.imei) {
            this.marker.setMap(null);
            //this.marker = objMapControl.addMarker(this.image, null, this.imeiDescription);
            this.marker.icon = objMapControl.getIconArrow(heading);
            this.marker.setMap(objMapControl.map)
        }
        else
            this.marker.icon = this.image;
            
        //this.marker = objMapControl.addMarkerDegree(this.position);
        objMapControl.setPositionMarker(this.marker, this.position);
        this.speed = speed;
        this.heading = heading;

        this.peopleIn = peopleIn;
        this.peopleOut = peopleOut;
        this.peopleInside = peopleInside;

        var content = "<b>Nombre: </b>" + this.imeiName + "<br>"
        content = content + "<b>Velocidad: </b>" + this.speed + "<br>";
        content = content + "<b>Ultimo Mensaje: </b>" + this.lastMessageImei + "<br>";

        objMapControl.addListenerMarkerClickForOpenWindowsInfo(this.marker, content);
    }

    //Se llaman directamente las sentencias de Google Map, si se invocan las opciones de objMapControl, el paso del parámetro pierde la variable de mapas o de longitudes.
    this.updateMinPosition = function (objMapControl, latitude, longitude, speed, map) {
        var latitude = parseFloat(latitude.toString().replace(",", "."));
        var longitude = parseFloat(longitude.toString().replace(",", "."));

        //this.lastMessageImei = lastMessageImei;

        this.position = new google.maps.LatLng(latitude, longitude);//objMapControl.addPosition(latitude, longitude);
        this.marker.setPosition(this.position);//objMapControl.setPositionMarker(this.marker, this.position);
        this.speed = speed;
        

        //this.peopleIn = peopleIn;
        //this.peopleOut = peopleOut;
        //this.peopleInside = peopleInside;
    }

    this.updateAlamsNotifications = function (pgeoferenceExitAlarm, pgeoferenceEnterAlarm, pSOSAlarm) {
        if (this.geoferenceExitAlarm != pgeoferenceExitAlarm && pgeoferenceExitAlarm == 'true') {

            addNotificationHistory('El Dispositivo ' + this.imeiDescription + ' salió del rango permitido.');
            showNotification('El Dispositivo salió del rango permitido.', this.imageLocation, this.imeiDescription);
        }

        this.geoferenceExitAlarm = pgeoferenceExitAlarm;

        if (this.geoferenceEnterAlarm != pgeoferenceEnterAlarm && pgeoferenceEnterAlarm == 'true') {
            addNotificationHistory('El Dispositivo ' + this.imeiDescription + ' ingreso al rango permitido.');
            showNotification('El Dispositivo ingreso al rango permitido.', this.imageLocation, this.imeiDescription);
        }

        this.geoferenceEnterAlarm = pgeoferenceEnterAlarm;

        if (this.sosAlarm != pSOSAlarm && pSOSAlarm == 'true') {
            addNotificationHistory('El Dispositivo ' + this.imeiDescription + ' ha activado la Alarma SOS.');
            showNotification('El Dispositivo ha activado la Alarma SOS.', this.imageLocation, this.imeiDescription);
        }

        this.sosAlarm = pSOSAlarm;
    }

    this.updateNotificationText = function (notificationTextList) {

        var isShowNotification;
        for (ik = 0; ik < notificationTextList.length; ik++)
        {
            isShowNotification = true;
            for (ij = 0; ij < this.notificationTextList.length; ij++) {    
                if (this.notificationTextList[ij] == notificationTextList[ik]) {
                    isShowNotification = false;
                }
            }
            if (isShowNotification) {
                this.showNotification(notificationTextList[ik], this.image.url, this.imeiName);
            }
        }
 
        this.notificationTextList = notificationTextList;
    }

    this.centerMarker = function (objMapControl) {
        objMapControl.setCenterMap(this.position);
    }

    this.showArrow = function (objMapControl) {
        this.marker.icon = objMapControl.getIconArrow(this.heading);
        objMapControl.setPositionMarker(this.marker, this.position);
    }

    this.showNotification = function (notification, imageLocation, titleNotification) {

        /*if (globalRoutes.showNotifications || globalRoutes.showNotificationsAlert) {

            if (globalRoutes.showNotificationsAlert)
            {
                globalRoutes.showNotificationsAlert = false;
                notification = '';
                //imageLocation = null;
                titleNotification = 'Las notificaciones están desabilitadas.';
            }
            */
        var havePermission = window.webkitNotifications.checkPermission();
        if (havePermission == 0) {
            // 0 is PERMISSION_ALLOWED
            //alert('con permiso');
            var notification = window.webkitNotifications.createNotification(
                imageLocation,
                titleNotification,
            notification
            );

            notification.onclick = function () {
                notification.close();
            }
            notification.show();
        } else {
            //alert('sin permiso');
            window.webkitNotifications.requestPermission();
        }
    }
}

function Notification(){
    var notificationID;
    var name;

    this.setNotification = function(notificationID, name){
        this.notificationID = notificationID;
        this.name = name;
    }
}

function NotificationsTrackData() {
    var gpsImei;
    var name;
    var notificationID;
    var datetime;
    var notificationText;

    this.setNotificationTrackData = function (gpsImei, name, notificationID, datetime, notificationText) {
        this.gpsImei = gpsImei;
        this.name = name;
        this.notificationID = notificationID;
        this.datetime = datetime;
        this.notificationText = notificationText;
    }
}

function GPSImeiNotification() {
    var gpsImei;
    var notificationText;

    this.setGPSImeiNotification = function (gpsImei, notificationText){
        this.gpsImei = gpsImei;
        this.notificationText = notificationText;
    }
}

//End Classes

//Begin Objects

function GPSImei() {

    this.showGPSImeiSelected = function (tree, opener) {
        var imei = this.getImeiValueTreeVehicleSelected(tree);
        for (ik = 0; ik < opener.globalMasterPage.trackDataLastLocationList.length; ik++) {
            if (imei == opener.globalMasterPage.trackDataLastLocationList[ik].imei) {

                opener.setInfoReal(ik);
                opener.showInfoReal(ik);
                opener.globalGPSImei.imeiSelected = imei;
                //opener.objMapControl.clearGeoFenceMarkers(true);

                //opener.objMapControl.zoomMap(16);

                //loadGeoFenceGridByImei(imei); trasladar al otro aspx.

                try {
                    if (opener.globalMasterPage.trackDataLastLocationList[ik].position == "(NaN, NaN)") {
                        objWindowsMessageManager.show_SmallError('No tiene coordenadas .', 'Posición GPS.');
                    }
                    else {
                        opener.globalMasterPage.trackDataLastLocationList[ik].centerMarker(opener.objMapControl);
                        //this.marker.icon = objMapControl.getIconArrow(heading);
                        //opener.globalMasterPage.trackDataLastLocationList[ik].marker.icon = objMapControl.getIconArrow(opener.globalMasterPage.trackDataLastLocationList[ik].heading);
                        opener.globalMasterPage.trackDataLastLocationList[ik].showArrow(opener.objMapControl);
                        opener.objMapControl.zoomMap(16);
                    }
                }
                catch (e) {
                    objWindowsMessageManager.show_SmallError('No tiene coordenadas', 'Posición GPS.');
                }
                return;
            }
        }
        return -1;
    }

    this.getImeiValueTreeVehicleSelected = function (tree) {
        var node = tree.get_selectedNode();
        if (node) {
            return node.get_value();
        }
        return -1;
    }

    this.openXMLTrackDataLastLocationGroupsImei = function (xmlObject, opener) {
        var xmlGroups = jQuery.parseXML(xmlObject);

        var lastGroupValue = "";
        var myTrackDataLastLocationImei;

        var gpsGroupID;
        var groupName;

        var imei;
        var imeiName;
        var imeiDescription;
        var imeiSimNumber;
        var imeiTypeID;
        var ImeiTypeIDDescription;
        var gpsModelID;
        var gpsModelIDName;
        var image;
        var lastMessageImei;
        var peopleIn;
        var peopleOut;
        var peopleInside;

        var latitude;
        var longitude;

        jQuery(xmlGroups).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                gpsGroupID = jQuery(this).find('GPSGroupID').text();
                groupName = jQuery(this).find('GPSGroupName').text();
                imei = jQuery(this).find('GPSImei').text();
                imeiName = jQuery(this).find('GPSImeiName').text();
                imeiDescription = jQuery(this).find('GPSImeiDescription').text();
                imeiTypeID = jQuery(this).find('GPSTypeID').text();
                ImeiTypeIDDescription = jQuery(this).find('GPSImeiTypeName').text();
                imeiSimNumber = jQuery(this).find('ImeiSimNumber').text();
                gpsModelID = jQuery(this).find('GPSModelID').text();
                gpsModelIDName = jQuery(this).find('GPSModelName').text();
                latitude = jQuery(this).find('Latitude').text();
                longitude = jQuery(this).find('Longitude').text();
                image = jQuery(this).find('Image').text();
                lastMessageImei = jQuery(this).find('LastMessageImei').text();
                peopleIn = jQuery(this).find('PeopleTotalIn').text();
                peopleOut = jQuery(this).find('PeopleTotlOut').text();
                peopleInside = jQuery(this).find('PeopleTotalInside').text();

                myTrackDataLastLocationImei = new TrackDataLastLocationImei();
                myTrackDataLastLocationImei.setInfo(opener.objMapControl, gpsGroupID, imei, imeiName, groupName, imeiDescription, imeiSimNumber, imeiTypeID, ImeiTypeIDDescription, latitude, longitude, image, lastMessageImei, peopleIn, peopleOut, peopleInside);

                if (GPSImei.getIndexImei(opener.globalMasterPage.trackDataLastLocationList, myTrackDataLastLocationImei.imei) == -1) {
                    opener.globalMasterPage.trackDataLastLocationList.push(myTrackDataLastLocationImei);
                }
            });
        });
    }

    this.openXMLTrackDataLastLocationByBusRoutes = function (xmlObject, opener, GPSImeiByBusRoutesList, map) {
        var xmlRoutes = jQuery.parseXML(xmlObject);

        var myTrackDataLastLocationImei;

        var imei;
        var imeiName;
        var imeiDescription;
        var image;
        var datetime;
        var latitude;
        var longitude;
        var speed;

        jQuery(xmlRoutes).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                
                imei = jQuery(this).find('GPSImei').text();
                imeiName = jQuery(this).find('GPSImeiName').text();
                imeiDescription = jQuery(this).find('GPSImeiDescription').text();
                image = jQuery(this).find('Image').text();
                datetime = jQuery(this).find('Datetime').text();
                latitude = jQuery(this).find('Latitude').text();
                longitude = jQuery(this).find('Longitude').text();
                speed = jQuery(this).find('Speed').text();

                myTrackDataLastLocationImei = new TrackDataLastLocationImei();
                myTrackDataLastLocationImei.setMinInfo(opener.objMapControl, imei, imeiName, imeiDescription, latitude, longitude, image, map);

                if (GPSImei.getIndexImei(GPSImeiByBusRoutesList, myTrackDataLastLocationImei.imei) == -1) {
                    GPSImeiByBusRoutesList.push(myTrackDataLastLocationImei);
                }
                
            });
        });
    }

    this.getIndexImei = function (list, imei) {
        for (ii = 0; ii < list.length; ii++) {
            if (imei == list[ii].imei) {
                return ii;
            }
        }
        return -1;
    }
    
    this.loadGPSImeiTree = function (tree, opener, searchText) {
        
        var nodeGroup;
        var nodeGroupInserted;
        var childNodeGPSImei;
        var lastGroupValue = "";

        var groupIDvehicle;

        for (i = 0; i < opener.globalMasterPage.trackDataLastLocationList.length; i++) {

            if (searchText == null || opener.globalMasterPage.trackDataLastLocationList[i].imeiName.toUpperCase().indexOf(searchText.toUpperCase()) > -1) {
                tree.trackChanges();

                nodeGroup = new Telerik.Web.UI.RadTreeNode();

                nodeGroup.set_value(opener.globalMasterPage.trackDataLastLocationList[i].gpsGroupID);
                nodeGroup.set_text(opener.globalMasterPage.trackDataLastLocationList[i].groupName);
                nodeGroup.set_expanded(true);

                childNodeGPSImei = new Telerik.Web.UI.RadTreeNode();

                childNodeGPSImei.set_value(opener.globalMasterPage.trackDataLastLocationList[i].imei);
                childNodeGPSImei.set_text(opener.globalMasterPage.trackDataLastLocationList[i].imeiName);
                childNodeGPSImei.set_imageUrl(opener.globalMasterPage.trackDataLastLocationList[i].image.url);

                if (lastGroupValue != groupIDvehicle) {
                    nodeGroupInserted = tree.findNodeByValue(opener.globalMasterPage.trackDataLastLocationList[i].gpsGroupID);
                }

                if (nodeGroupInserted == null) {
                    tree.get_nodes().add(nodeGroup);
                    nodeGroupInserted = tree.findNodeByValue(opener.globalMasterPage.trackDataLastLocationList[i].gpsGroupID);
                    tree.get_nodes().add(childNodeGPSImei);
                }

                nodeGroupInserted.get_nodes().add(childNodeGPSImei);

                lastGroupValue = opener.globalMasterPage.trackDataLastLocationList[i].gpsGroupID;

                tree.commitChanges();
            }
        }
    }
}

function ClientsProcess() {
    this.openXMLClientsProcess = function (xmlObject, list) {
        var xmlClientsControl = jQuery.parseXML(xmlObject);

        var username;
        var name;
        var gpsImei;
        var gpsName;
        var date;
        var timeBegin;
        var timeEnd;
        var status;
        var progress;
        var lastExecution;
        var clientGroupID;
        var clientGroupName;
        var latOrigin;
        var lngOrigin;

        clearList(list);
        var myClientsControl;

        jQuery(xmlClientsControl).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                username = jQuery(this).find('Username').text();
                name = jQuery(this).find('Name').text();
                gpsImei = jQuery(this).find('GPSImei').text();
                gpsName = jQuery(this).find('GPSName').text();
                date = jQuery(this).find('Date').text();
                timeBegin = jQuery(this).find('TimeBegin').text();
                timeEnd = jQuery(this).find('TimeEnd').text();
                status = jQuery(this).find('Status').text();
                progress = jQuery(this).find('Progress').text();
                lastExecution = jQuery(this).find('LastExecution').text();
                clientGroupID = jQuery(this).find('ClientGroupID').text();
                clientGroupName = jQuery(this).find('ClientGroupName').text();
                latOrigin = jQuery(this).find('LatitudeOrigin').text();
                lngOrigin = jQuery(this).find('LongitudeOrigin').text();


                myClientsControl = new ClientsControl();
                myClientsControl.setClientsControl(username, name, gpsImei, gpsName, date, timeBegin, timeEnd, status, progress, lastExecution, clientGroupID, clientGroupName, latOrigin, lngOrigin);

                list.push(myClientsControl);
                //if (VPCProcesses.getIndexNumControl(opener.globalBusStopsRouteHistory.vpcProcessList, myVPCProcess.numControl) == -1) {
                //    list.push(myVPCProcess);
                //}
            });
        });
    }

    /*this.getIndexNumControl = function (list, imei) {
        for (ii = 0; ii < list.length; ii++) {
            if (imei == list[ii].imei) {
                return ii;
            }
        }
        return -1;
    }*/

    this.loadClientsProcessDataSource = function (tableView, list, dataSource) {

        //if (dataSource.length == 0) {
        clearDataSource(dataSource, tableView, true);
        for (iii = 0; iii < list.length; iii++) {
            dataSource.push({ "Username": list[iii].username, "Name": list[iii].name, "GPSImei": list[iii].gpsImei, "GPSName": list[iii].gpsName, "Date": list[iii].date, "TimeBegin": list[iii].timeBegin, "TimeEnd": list[iii].timeEnd, "Status": list[iii].status, "Process": list[iii].process, "LastExecution": list[iii].lastExecution, "ClientGroupID": list[iii].clientGroupID, "ClientGroupName": list[iii].clientGroupName, "LatOrigin": list[iii].latOrigin, "LngOrigin": list[iii].lngOrigin });
        }
        //}

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.hideObjects = function (globalObject, objMapControl, list) {
        var length = list.length;
        for (i = 0; i < length; i++) {
            objMapControl.setVisibleMarker(list[i].marker, false);
        }
        objMapControl.hideDirectionsDisplay(globalObject.directionsDisplay);
        objMapControl.setVisibleMarker(globalObject.GPSImeiRoute, false);
    }

    this.showObjects = function (globalObject, objMapControl, list) {
        var length = list.length;
        for (i = 0; i < length; i++) {
            objMapControl.setVisibleMarker(list[i].marker, true);
        }
        objMapControl.showDirectionsDisplay(globalObject.directionsDisplay);
        objMapControl.setVisibleMarker(globalObject.GPSImeiRoute, true);
    }

    this.clearClientsToVisit = function (opener) {
        var length = opener.globalClientsRouteHistory.clientsToVisitList.length;

        for (i = 0; i < length; i++) {
            opener.objMapControl.clearMarkerFromMap(opener.globalClientsRouteHistory.clientsToVisitList[length - 1 - i].marker);
            opener.globalClientsRouteHistory.clientsToVisitList.pop();
        }

        if (opener.globalClientsRouteHistory.routesList.length > 0) {

            length = opener.globalClientsRouteHistory.routesList[0].legs.length;

            for (i = 0; i < length; i++) {
                opener.globalClientsRouteHistory.routesList[0].legs.pop();
            }

            opener.globalClientsRouteHistory.response.routes = opener.globalClientsRouteHistory.routesList;
            opener.objMapControl.hideDirectionsDisplay(opener.globalClientsRouteHistory.directionsDisplay);
        }

        clearList(opener.globalClientsRouteHistory.polygonoRouteMarkers);

    }

    this.openCollectionStringProcessDetailsFirsSelection = function (stringCollection, opener, globalObject) {

        //this.hideHistoryRoute(opener);

        //opener.objMapControl.hideHistoryRoute();

        totalList = globalObject.trackDataByImei.length;
        for (k = 0; k < totalList; k++) {
            globalObject.trackDataByImei.pop();
        }
        //mycar.setPosition(null);
        //opener.objMapControl.setPositionMarker(opener.objMapControl.GPSImeiRoute, null);

        //var xmlImei = jQuery.parseXML(xmlObject);

        //var kmAnterior;
        //var kmActual;
        //var kmtotal;

        var imei;
        var hour;
        var latitude;
        var longitude;
        var speed;
        var imageLocation;

        var myTrackData;
        var myLastTrackData = null;

        var distanceKm;
        var totalKm;

        var info = [];

        for (i = 0; i < stringCollection.length; i++) {

            info = [];

            info = stringCollection[i].split('&');

            if (i == 0) {
                imei = info[0];
                imageLocation = info[1];
            }
            else {
                hour = info[0];
                speed = info[1];
                latitude = info[2];
                longitude = info[3];
                totalKm = info[4];
                distanceKm = info[5];

                myTrackData = new TrackData();

                //kmAnterior = 0;
                //kmActual = 0;
                //kmtotal = 0;

                myTrackData.setTrackData(opener.objMapControl, imei, speed, latitude, longitude, imageLocation, hour, 0, 0, 0, 0, 0);
                myTrackData.setAditionalInfo(0, distanceKm, totalKm);

                /*if (myLastTrackData != null) {
                    kmAnterior = myLastTrackData.currentKm;
                    kmActual = opener.objMapControl.getDistanceKms(myLastTrackData.position, myTrackData.position);

                    kmtotal = parseFloat(kmAnterior) + parseFloat(kmActual);
                    myTrackData.currentKm = kmtotal;
                }
                else {
                    myTrackData.currentKm = 0;
                }*/

                globalObject.trackDataByImei.push(myTrackData);
                myLastTrackData = myTrackData;
            }
        }
    }

    this.openXMLResumenProcessDetails = function (xmlObject, opener) {
        var xmlResumen = jQuery.parseXML(xmlObject);

        jQuery(xmlResumen).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                opener.globalBusStopsRouteHistory.peopleTotalOut = jQuery(this).find('PeopleTotalOut').text();
                opener.globalBusStopsRouteHistory.peopleTotalIn = jQuery(this).find('PeopleTotalIn').text();
                opener.globalBusStopsRouteHistory.totalTrack = jQuery(this).find('TotalTrack').text();
                opener.globalBusStopsRouteHistory.totalKm = jQuery(this).find('TotalKm').text();
            });
        });
    }

    this.openXMLClientsByCompanyIDAndUsernameAndGPSImeiAndDate = function (objMapControl, xmlObject, list) {
        var xmlClients = jQuery.parseXML(xmlObject);

        var numPos;
        var clientID;
        var clientName;
        var arriveDateTime;
        var dateTimeEnd;
        var distanceKmTravel;
        var latitude;
        var longitude;
        var hoursTravel;
        var minutesTravel;
        var hours;
        var minutes;

        var myClientsToVisit;

        jQuery(xmlClients).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                numPos = jQuery(this).find('NumPos').text();
                clientID = jQuery(this).find('ClientID').text();
                clientName = jQuery(this).find('ClientName').text();
                arriveDateTime = jQuery(this).find('ArriveDateTime').text();
                dateTimeEnd = jQuery(this).find('DateTimeEnd').text();
                distanceKmTravel = jQuery(this).find('DistanceKmTravel').text();
                latitude = jQuery(this).find('Latitude').text();
                longitude = jQuery(this).find('Longitude').text();
                hoursTravel = jQuery(this).find('HoursTravel').text();
                minutesTravel = jQuery(this).find('MinutesTravel').text();
                hours = jQuery(this).find('Hours').text();
                minutes = jQuery(this).find('Minutes').text();

                myClientsToVisit = new ClientsToVisit();
                myClientsToVisit.setClientsToVisit(objMapControl, numPos, clientID, clientName, arriveDateTime, dateTimeEnd, distanceKmTravel, latitude, longitude, hoursTravel, minutesTravel, hours, minutes);

                list.push(myClientsToVisit);
            });
        });
    }
}

function VPCProcesses() {
    this.openXMLVPCPocess = function (xmlObject, list) {
        var xmlGroups = jQuery.parseXML(xmlObject);

        var numControl;
        var numCard;
        var driverID;
        var driverName;
        var gpsImei
        var gpsImeiName;
        var busRouteID;
        var busRouteName;
        var date;
        var timeBegin;
        var timeEnd;
        var status;
        var progress;
        var lastExecution;

        clearList(list);

        jQuery(xmlGroups).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                numControl = jQuery(this).find('NumControl').text();
                numCard = jQuery(this).find('NumCard').text();
                driverID = jQuery(this).find('DriverID').text();
                driverName = jQuery(this).find('DriverName').text();
                gpsImei = jQuery(this).find('GPSImei').text();
                gpsImeiName = jQuery(this).find('GPSImeiName').text();
                busRouteID = jQuery(this).find('BusRouteID').text();
                busRouteName = jQuery(this).find('BusRouteName').text();
                date = jQuery(this).find('Date').text();
                timeBegin = jQuery(this).find('TimeBegin').text();
                timeEnd = jQuery(this).find('TimeEnd').text();
                status = jQuery(this).find('Status').text();
                progress = jQuery(this).find('Progress').text();
                lastExecution = jQuery(this).find('LastExecution').text();
                
                myVPCProcess = new VPCProcess();
                myVPCProcess.setVPCControl(numControl, numCard, driverID, driverName, gpsImei, gpsImeiName, busRouteID, busRouteName, date, timeBegin, timeEnd, status, progress, lastExecution);

                if (VPCProcesses.getIndexNumControl(opener.globalBusStopsRouteHistory.vpcProcessList, myVPCProcess.numControl) == -1) {
                    list.push(myVPCProcess);
                }
            });
        });
    }

    this.getIndexNumControl = function (list, imei) {
        for (ii = 0; ii < list.length; ii++) {
            if (imei == list[ii].imei) {
                return ii;
            }
        }
        return -1;
    }

    this.loadVPCProcessDataSource = function (tableView, list, dataSource) {

        //if (dataSource.length == 0) {
        clearDataSource(dataSource, tableView, true);
            for (iii = 0; iii < list.length; iii++) {
                dataSource.push({"NumControl": list[iii].numControl, "NumCard": list[iii].numCard, "DriverID": list[iii].driverID, "DriverName": list[iii].driverName, "GPSImei": list[iii].gpsImei, "GPSImeiName": list[iii].gpsImeiName, "BusRouteID": list[iii].busRouteID, "BusRouteName": list[iii].busRouteName, "Date": list[iii].date, "TimeBegin": list[iii].timeBegin, "TimeEnd": list[iii].timeEnd, "Status": list[iii].status, "Process": list[iii].process, "LastExecution": list[iii].lastExecution});
            }
        //}

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.clearBusRoutes = function (opener) {
        var length = opener.globalBusStopsRouteHistory.busStopsList.length;

        for (i = 0; i < length; i++) {
            opener.objMapControl.clearMarkerFromMap(opener.globalBusStopsRouteHistory.busStopsList[length - 1 - i].marker);
            opener.globalBusStopsRouteHistory.busStopsList.pop();
        }

        if (opener.globalBusStopsRouteHistory.busRoutesList.length > 0) {

            length = opener.globalBusStopsRouteHistory.busRoutesList[0].legs.length;

            for (i = 0; i < length; i++) {
                opener.globalBusStopsRouteHistory.busRoutesList[0].legs.pop();
            }

            opener.globalBusStopsRouteHistory.response.routes = opener.globalBusStopsRouteHistory.busRoutesList;
            opener.objMapControl.hideDirectionsDisplay(opener.globalBusStopsRouteHistory.directionsDisplay);
        }

        clearList(opener.globalBusStopsRouteHistory.polygonoBusRouteMarkers);

    }

    this.hideObjects = function (globalObject, objMapControl, list) {
        var length = list.length;
        for (i = 0; i < length; i++) {
            objMapControl.setVisibleMarker(list[i].marker, false);
        }
        objMapControl.hideDirectionsDisplay(globalObject.directionsDisplay);
        objMapControl.setVisibleMarker(globalObject.GPSImeiRoute, false);
    }

    this.showObjects = function (globalObject, objMapControl, list) {
        var length = list.length;
        for (i = 0; i < length; i++) {
            objMapControl.setVisibleMarker(list[i].marker, true);
        }
        objMapControl.showDirectionsDisplay(globalObject.directionsDisplay);
        objMapControl.setVisibleMarker(globalObject.GPSImeiRoute, true);
    }

    this.openCollectionStringProcessDetailsFirsSelection = function (stringCollection, opener, globalObject) {

        //this.hideHistoryRoute(opener);

        //opener.objMapControl.hideHistoryRoute();

        totalList = globalObject.trackDataByImei.length;
        for (k = 0; k < totalList; k++) {
            globalObject.trackDataByImei.pop();
        }
        //mycar.setPosition(null);
        //opener.objMapControl.setPositionMarker(opener.objMapControl.GPSImeiRoute, null);

        //var xmlImei = jQuery.parseXML(xmlObject);

        //var kmAnterior;
        //var kmActual;
        //var kmtotal;

        var imei;
        var hour;
        var latitude;
        var longitude;
        var speed;
        var imageLocation;

        var myTrackData;
        var myLastTrackData = null;

        var peopleIn;
        var peopleOut;
        var peopleTotalInside;
        var peopleTotalIn;
        var peopleTotalOut;
        var totalTrack;
        var distanceKm;
        var totalKm;

        var info = [];

        for (i = 0; i < stringCollection.length; i++) {

            info = [];

            info = stringCollection[i].split('&');

            if (i == 0) {
                imei = info[0];
                imageLocation = info[1];
            }
            else {
                hour = info[0];
                speed = info[1];
                latitude = info[2];
                longitude = info[3];
                peopleIn = info[4];
                peopleOut = info[5];
                peopleInside = info[6];
                peopleTotalIn = info[7];
                peopleTotalOut = info[8];

                totalTrack = info[9];
                totalKm = info[10];
                distanceKm = info[11];

                myTrackData = new TrackData();

                //kmAnterior = 0;
                //kmActual = 0;
                //kmtotal = 0;

                myTrackData.setTrackData(opener.objMapControl, imei, speed, latitude, longitude, imageLocation, hour, peopleIn, peopleOut, peopleTotalInside, peopleTotalIn, peopleTotalOut);
                myTrackData.setAditionalInfo(totalTrack, distanceKm, totalKm);

                /*if (myLastTrackData != null) {
                    kmAnterior = myLastTrackData.currentKm;
                    kmActual = opener.objMapControl.getDistanceKms(myLastTrackData.position, myTrackData.position);

                    kmtotal = parseFloat(kmAnterior) + parseFloat(kmActual);
                    myTrackData.currentKm = kmtotal;
                }
                else {
                    myTrackData.currentKm = 0;
                }*/

                globalObject.trackDataByImei.push(myTrackData);
                myLastTrackData = myTrackData;
            }
        }
    }

    this.openXMLResumenProcessDetails = function (xmlObject, opener) {
        var xmlResumen = jQuery.parseXML(xmlObject);

        jQuery(xmlResumen).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                opener.globalBusStopsRouteHistory.peopleTotalOut = jQuery(this).find('PeopleTotalOut').text();
                opener.globalBusStopsRouteHistory.peopleTotalIn = jQuery(this).find('PeopleTotalIn').text();
                opener.globalBusStopsRouteHistory.totalTrack = jQuery(this).find('TotalTrack').text();
                opener.globalBusStopsRouteHistory.totalKm = jQuery(this).find('TotalKm').text();
            });
        });
    }

}

function Companies() {
    this.openXMLCompaniesByAdminUsername = function (xmlObject, list) {
        var xmlCompanies = jQuery.parseXML(xmlObject);

        var companyID;
        var name;

        var myCompany;

        jQuery(xmlCompanies).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                companyID = jQuery(this).find('CompanyID').text();
                name = jQuery(this).find('Name').text();
                myCompany = new Company();
                myCompany.setCompany(companyID, name);

                list.push(myCompany);
            });
        });
    }

    this.loadCompaniesDataSource = function (tableView, list, dataSource) {

        if (dataSource.length == 0) {
            for (iii = 0; iii < list.length; iii++) {
                dataSource.push({ "CompanyID": list[iii].companyID, "Name": list[iii].name });
            }
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.getIndexCompanyID = function (list, companyID) {
        for (ii = 0; ii < list.length; ii++) {
            if (list[ii].companyID == companyID) {
                return ii;
            }
        }
        return -1;
    }
}

function NotificationManager() {

    this.openXMLNotifications = function (xmlObject, list) {
        var xmlNotifications = jQuery.parseXML(xmlObject);

        var notificationID;
        var name;

        var myNotification;

        jQuery(xmlNotifications).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                notificationID = jQuery(this).find('NotificationID').text();
                name = jQuery(this).find('Name').text();

                myNotification = new Notification();
                myNotification.setNotification(notificationID, name);

                list.push(myNotification);
            });
        });
    }

    this.loadNotificationDataSource = function (tableView, list, dataSource) {

        if (dataSource.length == 0) {
            for (iii = 0; iii < list.length; iii++) {
                dataSource.push({ "NotificationID": list[iii].notificationID, "Name": list[iii].name });
            }
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.openXMLGPSGroups = function (xmlObject, list) {
        var xmlGPSGroups = jQuery.parseXML(xmlObject);

        var gpsGroupID;
        var name;

        var myGPSGroup;

        jQuery(xmlGPSGroups).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                gpsGroupID = jQuery(this).find('GPSGroupID').text();
                name = jQuery(this).find('Name').text();

                myGPSGroup = new GPSGroup();
                myGPSGroup.setGPSGroup(gpsGroupID, name);

                list.push(myGPSGroup);
            });
        });
    }

    this.loadGPSGroupDataSource = function (tableView, list, dataSource) {

        if (dataSource.length == 0) {
            for (iii = 0; iii < list.length; iii++) {
                dataSource.push({ "GPSGroupID": list[iii].gpsGroupID, "Name": list[iii].name });
            }
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.openXMLGPSStock = function (xmlObject, list, opener) {
        var xmlGPSStock = jQuery.parseXML(xmlObject);

        var index;
        var gpsImei;
        var name;
        var lastAction;
        var currentAction;
        var sendToAdmin;
        var sendToUser;

        var myGPSStock;

        jQuery(xmlGPSStock).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                index = jQuery(this).find('Index').text();
                gpsImei = jQuery(this).find('GPSImei').text();
                name = jQuery(this).find('Name').text();
                lastAction = jQuery(this).find('LastAction').text();
                sendToAdmin = jQuery(this).find('SendToAdmin').text();
                sendToUser = jQuery(this).find('SendToUser').text();

                currentAction = lastAction;

                myGPSStock = new GPSStock();
                myGPSStock.setGPSStock(index, gpsImei, name, lastAction, currentAction);

                list.push(myGPSStock);
            });
        });

        if (list.length > 0) {
            if (sendToAdmin == "false") {
                opener.globalNotificationManager.lastNotyGeoFenceToSendAdmin = false;
                opener.globalNotificationManager.currentNotyGeoFenceToSendAdmin = false;
            }
            if (sendToAdmin == "true") {
                opener.globalNotificationManager.lastNotyGeoFenceToSendAdmin = true;
                opener.globalNotificationManager.currentNotyGeoFenceToSendAdmin = true;
            }
            if (sendToUser == "false") {
                opener.globalNotificationManager.lastNotyGPSImeiToSendUser = false;
                opener.globalNotificationManager.currentNotyGPSImeiToSendUser = false;
            }
            if (sendToUser == "true") {
                opener.globalNotificationManager.lastNotyGPSImeiToSendUser = true;
                opener.globalNotificationManager.currentNotyGPSImeiToSendUser = true;
            }
        }
    }

    this.loadGPSStockDataSource = function (tableView, list, dataSource) {

        if (dataSource.length == 0) {
            for (iii = 0; iii < list.length; iii++) {
                dataSource.push({ "GPSImei": list[iii].gpsImei, "Name": list[iii].name });
            }
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();

        for (iii = 0; iii < list.length; iii++) {
            if (list[iii].lastAction == "I") {
                tableView.selectItem(list[iii].index);
            }
        }

    }

    this.clearAllPolygonoGeoFenceList = function (opener) {
        for (i = 0; i < opener.globalNotificationManager.geoFencesList.length; i++) {
            if (opener.globalNotificationManager.geoFencesList[i].checked) {
                opener.globalNotificationManager.geoFencesList[i].checked = false;
                opener.globalNotificationManager.geoFencesList[i].hideGeoFence(opener);
            }
        }
    }

    this.getIndexGPSImei = function (list, gpsImei) {
        for (ii = 0; ii < list.length; ii++) {
            if (list[ii].gpsImei == gpsImei) {
                return ii;
            }
        }
        return -1;
    }

    this.getIndexGPSGroupID = function (list, gpsGroupID) {
        for (ii = 0; ii < list.length; ii++) {
            if (list[ii].gpsGroupID == gpsGroupID) {
                return ii;
            }
        }
        return -1;
    }

    this.getIndexNotificationID = function (list, notificationID) {
        for (ii = 0; ii < list.length; ii++) {
            if (list[ii].notificationID == notificationID) {
                return ii;
            }
        }
        return -1;
    }

    this.isValidToInsertNotifications = function (opener) {

        if (opener.globalNotificationManager.companyIDSelected != -1) {
            if (opener.globalNotificationManager.notificationIDSelected != -1) {
                if (opener.globalNotificationManager.geoFenceIDSelected != -1) {
                    if (opener.globalNotificationManager.gpsGroupIDSelected != -1) {
                        clearList(opener.globalNotificationManager.gpsImeiListToInsert);
                        clearList(opener.globalNotificationManager.gpsImeiListToDelete);

                        for (i = 0; i < opener.globalNotificationManager.gpsStockList.length; i++) {
                            if (opener.globalNotificationManager.gpsStockList[i].lastAction != opener.globalNotificationManager.gpsStockList[i].currentAction) {
                                if (opener.globalNotificationManager.gpsStockList[i].currentAction == "I") {
                                    opener.globalNotificationManager.gpsImeiListToInsert.push(opener.globalNotificationManager.gpsStockList[i].gpsImei);
                                }
                                else {
                                    opener.globalNotificationManager.gpsImeiListToDelete.push(opener.globalNotificationManager.gpsStockList[i].gpsImei);
                                }
                            }
                        }

                        if (opener.globalNotificationManager.currentNotyGPSImeiToSendUser != opener.globalNotificationManager.lastNotyGPSImeiToSendUser) {
                            opener.globalNotificationManager.isUpdateNotyGPSImeiToSendUser = true;
                        }
                        else {
                            opener.globalNotificationManager.isUpdateNotyGPSImeiToSendUser = false;
                        }

                        if (opener.globalNotificationManager.currentNotyGeoFenceToSendAdmin != opener.globalNotificationManager.lastNotyGeoFenceToSendAdmin) {
                            opener.globalNotificationManager.isUpdateNotyGeoFenceToSendAdmin = true;
                        }
                        else {
                            opener.globalNotificationManager.isUpdateNotyGeoFenceToSendAdmin = false;
                        }

                        if (opener.globalNotificationManager.gpsImeiListToDelete.length == 0 && opener.globalNotificationManager.gpsImeiListToInsert.length == 0 && !opener.globalNotificationManager.isUpdateNotyGeoFenceToSendAdmin && !opener.globalNotificationManager.isUpdateNotyGPSImeiToSendUser) {
                            objWindowsMessageManager.show_Warning("No hay cambios seleccionado para asociar.", titles.notifications, opener.globalNotificationManager.widthForMsg);
                            return false;
                        }

                        return true;
                    }
                    else {
                        objWindowsMessageManager.show_Warning("Debe seleccionar un Grupo de GPSImei", titles.notifications, opener.globalNotificationManager.widthForMsg);
                        return false;
                    }
                }
                else {
                    objWindowsMessageManager.show_Warning("Debe seleccionar una Geo Cerca", titles.notifications, opener.globalNotificationManager.widthForMsg);
                    return false;
                }
            }
            else {
                objWindowsMessageManager.show_Warning("Debe seleccionar una Notificación", titles.notifications, opener.globalNotificationManager.widthForMsg);
                return false;
            }
        }
        else {
            objWindowsMessageManager.show_Warning("Debe seleccionar una Companía", titles.notifications, opener.globalNotificationManager.widthForMsg);
            return false;
        }
    }
}

function ClientManager() {

    this.openXMLClientsGroupsByCompanyID = function (xmlObject, list) {
        var xmlClientsGroups = jQuery.parseXML(xmlObject);

        var clientGroupID;
        var name;

        var myClientGroup;

        jQuery(xmlClientsGroups).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                clientGroupID = jQuery(this).find('ClientGroupID').text();
                name = jQuery(this).find('Name').text();
                myClientGroup = new ClientGroup();
                myClientGroup.setClientGroup(clientGroupID, name);

                list.push(myClientGroup);
            });
        });
    }

    this.openXMLClientsByCompanyAndClientGroupID = function (objMapControl, xmlObject, list) {
        var xmlClients = jQuery.parseXML(xmlObject);

        var clientID;
        var name;
        var latitude;
        var longitude;

        var myClient;

        jQuery(xmlClients).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                clientID = jQuery(this).find('ClientID').text();
                name = jQuery(this).find('Name').text();
                latitude = jQuery(this).find('Latitude').text();
                longitude = jQuery(this).find('Longitude').text();
                myClient = new Client();
                myClient.setClient(objMapControl, clientID, name, latitude, longitude, objMapControl);

                list.push(myClient);
            });
        });
    }

    this.loadClientsGroupsDataSource = function (tableView, list, dataSource) {

        if (dataSource.length == 0) {
            for (iii = 0; iii < list.length; iii++) {
                dataSource.push({ "ClientGroupID": list[iii].clientGroupID, "Name": list[iii].name });
            }
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.loadClientsDataSource = function(tableView, list, dataSource) {

        for (iii = 0; iii < list.length; iii++) {
            dataSource.push({ "ClientID": list[iii].clientID, "Name": list[iii].clientName });
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.getIndexClientGroupID = function (list, clientGroupID) {
        for (ii = 0; ii < list.length; ii++) {
            if (list[ii].clientGroupID == clientGroupID) {
                return ii;
            }
        }
        return -1;
    }

    this.getIndexClientID = function (list, clientID) {
        for (ii = 0; ii < list.length; ii++) {
            if (list[ii].clientID == clientID) {
                return ii;
            }
        }
        return -1;
    }

    this.getIndexCompanyID = function (list, companyID) {
        for (ii = 0; ii < list.length; ii++) {
            if (list[ii].companyID == companyID) {
                return ii;
            }
        }
        return -1;
    }

    this.showAllClientsChecked = function (list) {
        for (lk = 0; lk < list.length; lk++) {
            list[lk].marker.setVisible(list[lk].checked);                       
        }
    }

    this.hideAllClientsSelected = function (list) {
        for (lk = 0; lk < list.length; lk++) {
            list[lk].marker.setVisible(false);
        }
    }

    this.clearSelection = function (tableView, list) {
        for (k = 0; k < list.length; k++) {
            list[k].checked = false;
            tableView.clearSelectedItems();
        }
    }

    this.enableDisableClientEventClickMap = function (opener, checked) {
        if (checked) {
            //getCkbEnableDisableGeoFence().checked = false;
            opener.objMapControl.clearListenerClic();
            //objMapControl.clearGeoFenceMarkers(false);
            opener.objMapControl.setVisibleMarker(opener.globalClientManager.clientMarker, true);
            opener.objMapControl.addListenerClientClick();
        }
        else {
            opener.objMapControl.clearListenerClic();
            opener.objMapControl.setVisibleMarker(opener.globalClientManager.clientMarker, false);
            opener.objMapControl.setPositionMarker(opener.globalClientManager.clientMarker, null);
        }
    }

    this.isValidToInsertClient = function (opener, objects) {
        try {
            opener.objMapControl.getPositionMarker(opener.globalClientManager.clientMarker);
            objects.lat = stringToFloatForPosition(opener.objMapControl.getPositionXtoString(opener.objMapControl.getPositionMarker(opener.globalClientManager.clientMarker)));
            objects.lng = stringToFloatForPosition(opener.objMapControl.getPositionYtoString(opener.objMapControl.getPositionMarker(opener.globalClientManager.clientMarker)));
        }
        catch (e) {
            objWindowsMessageManager.show_Warning("No se ha ingresado el marcador del Cliente.", titles.clientTitle);
            return false;
        }

        if (opener.globalClientManager.companyID != -1) {
            if (opener.globalClientManager.clientGroupID != -1) {
                if (objects.clientName != "") {
                    return true;
                }
                else {
                    objWindowsMessageManager.show_Warning("No se ha ingresado el nombre del cliente.", titles.clientTitle);
                    return false;
                }
            }
            else {
                objWindowsMessageManager.show_Warning("No se ha seleccionado el grupo de clientes.", titles.clientTitle);
                return false;
            }
        }
        else {
            objWindowsMessageManager.show_Warning("No se ha seleccionado la compañia.", titles.clientTitle);
            return false;
        }
    }

    this.isValidToGetClients = function (opener, clientGroupID, tableView)
    {
        //if (opener.globalClientManager.clientGroupID != clientGroupID) {

            this.clearSelection(tableView, opener.globalClientManager.clientsList);
            clearList(opener.globalClientManager.clientsList);
            clearDataSource(opener.globalClientManager.clientsDataSource, tableView, true);

            index = this.getIndexClientGroupID(opener.globalClientManager.clientsGroupsList, clientGroupID);

            if (index != -1) {
                opener.globalClientManager.clientsGroupsList[index].checked = true;
                opener.globalClientManager.clientGroupID = clientGroupID;
                return true;
            }
            else{
                return false;
            }
        //}

        //return false;
    }

    this.isValidToGetClientsGroups = function (opener, companyID, tableView) {
        if (opener.globalClientManager.companyID != companyID) {

            this.clearSelection(tableView, opener.globalClientManager.clientsList);
            clearList(opener.globalClientManager.clientsList);
            clearDataSource(opener.globalClientManager.clientsDataSource, tableView, true);
            index = this.getIndexCompanyID(opener.globalClientManager.companiesList, companyID);

            if (index != -1) {
                opener.globalClientManager.companiesList[index].checked = true;
                opener.globalClientManager.companyID = companyID;
                return true;
            }
            else {
                return false;
            }
        }

        return false;
    }

    this.clientGridRowSelecting = function (opener, args, isZoom, isCenter)
    {
        var index = -1;
        var clientID;
        try {
            if (args._domEvent.target.cellIndex != 0) {
                clientID = args.getDataKeyValue("ClientID");
                index = ClientManager.getIndexClientID(opener.globalClientManager.clientsList, clientID);
                if (index != -1) {
                    opener.globalClientManager.clientsList[index].checked = true;
                    if (isCenter) {
                        opener.objMapControl.centerMap(opener.objMapControl.getPositionMarker(opener.globalClientManager.clientsList[index].marker));
                    }
                    if (isZoom) {
                        opener.objMapControl.zoomMap(16);
                    }
                    ClientManager.showAllClientsChecked(opener.globalClientManager.clientsList);
                }
            }
            else {
                index = ClientManager.getIndexClientID(opener.globalClientManager.clientsList, args.getDataKeyValue("ClientID"));
                if (index != -1) {
                    args.set_cancel(true);
                }
            }
        }
        catch (e) {
            null;
        }
    }

    this.clientInsertSuccessful = function (opener, id, tree, clientName) {
        var myClient = new Client();
        myClient.setClient(opener.objMapControl, id, clientName, opener.objMapControl.getPositionXtoString(opener.objMapControl.getPositionMarker(opener.globalClientManager.clientMarker)), opener.objMapControl.getPositionYtoString(opener.objMapControl.getPositionMarker(opener.globalClientManager.clientMarker)));
        myClient.checked = true;
        opener.globalClientManager.clientsList.push(myClient);
        clearDataSource(opener.globalClientManager.clientsDataSource, tree, false);
        this.loadClientsDataSource(tree, opener.globalClientManager.clientsList, opener.globalClientManager.clientsDataSource);
        this.showAllClientsChecked(opener.globalClientManager.clientsList);
        this.selectLastItemByClient(tree, opener.globalClientManager.clientsList);
        opener.objMapControl.setPositionMarker(opener.globalClientManager.clientMarker, null);
    }

    this.selectLastItemByClient = function(masterTable, list) {
        masterTable.selectItem(list.length - 1);
    }

    this.clientGridOnRowClick = function (opener, args) {
        if (args._domEvent.target.cellIndex == 0) {// La columna 0 Representa la columna de eliminar
            var index = this.getIndexClientID(opener.globalClientManager.clientsList, args.getDataKeyValue("ClientID"));
            if (index != -1) {
                if (confirm('¿Desea eliminar el Cliente?')) {
                    opener.globalClientManager.clientID = args.getDataKeyValue("ClientID");
                    return true;
                }
            }
        }
        return false;
    }

    this.refreshAfterDeleteClient = function (opener, tree) {
        for (i = 0; i < opener.globalClientManager.clientsList.length; i++) {

            if (opener.globalClientManager.clientID == opener.globalClientManager.clientsList[i].clientID) {
                opener.globalClientManager.clientsList[i].marker.setMap(null);
                opener.globalClientManager.clientsList.splice(i, 1);
            }
        }

        //this.clearSelection(tree, opener.globalClientManager.clientsList);
        clearDataSource(opener.globalClientManager.clientsDataSource, tree, true);
        this.loadClientsDataSource(tree, opener.globalClientManager.clientsList, opener.globalClientManager.clientsDataSource);
    }

}

function BusStopsManager() {

    this.openXMLBusRoutesByCompanyID = function (xmlObject, list) {
        var xmlBusRoutes = jQuery.parseXML(xmlObject);

        var busRouteID;
        var name;

        var myBusRoute;

        jQuery(xmlBusRoutes).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                busRouteID = jQuery(this).find('BusRouteID').text();
                name = jQuery(this).find('Name').text();
                myBusRoute = new BusRoute();
                myBusRoute.setBusRoute(busRouteID, name);

                list.push(myBusRoute);
            });
        });
    }

    this.openXMLBusStopsByCompanyAndBusRouteID = function (objMapControl, xmlObject, list) {
        var xmlBusStops = jQuery.parseXML(xmlObject);

        var busStopID;
        var name;
        var latitude;
        var longitude;

        var myBusStop;

        jQuery(xmlBusStops).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                busStopID = jQuery(this).find('BusStopID').text();
                name = jQuery(this).find('Name').text();
                latitude = jQuery(this).find('Latitude').text();
                longitude = jQuery(this).find('Longitude').text();
                myBusStop = new BusStop();
                myBusStop.setBusStop(objMapControl, busStopID, name, latitude, longitude, objMapControl);

                list.push(myBusStop);
            });
        });
    }

    this.openXMLBusRouteDetailsByBusRouteID = function (xmlObject, globalObject) {
        var xmlBusRoutes = jQuery.parseXML(xmlObject);

        var pos;
        var latitude;
        var longitude;

        globalObject.temporalyList = [];

        jQuery(xmlBusRoutes).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                pos = jQuery(this).find('Pos').text();
                latitude = jQuery(this).find('Latitude').text();
                longitude = jQuery(this).find('Longitude').text();

                globalObject.temporalyList.push(opener.objMapControl.addPosition(stringToFloatForPosition(latitude), stringToFloatForPosition(longitude)));
            });
        });
    }

    this.clearBusRoutes = function (opener) {
        var length = opener.globalBusStopsManager.polygonoBusRouteMarkers.length;
        
        for (i = 0; i < length; i++) {
            opener.objMapControl.clearMarkerFromMap(opener.globalBusStopsManager.polygonoBusRouteMarkers[length - 1 - i]);
            opener.globalBusStopsManager.polygonoBusRouteMarkers.pop();
        }

        if (opener.globalBusStopsManager.busRoutes.length > 0) {

            length = opener.globalBusStopsManager.busRoutes[0].legs.length;

            for (i = 0; i < length; i++) {
                opener.globalBusStopsManager.busRoutes[0].legs.pop();
            }

            opener.globalBusStopsManager.response.routes = opener.globalBusStopsManager.busRoutes;
            opener.objMapControl.hideDirectionsDisplay(opener.globalBusStopsManager.directionsDisplay);
        }
    }

    this.loadBusRoutesDataSource = function (tableView, list, dataSource) {

        if (dataSource.length == 0) {
            for (iii = 0; iii < list.length; iii++) {
                dataSource.push({ "BusRouteID": list[iii].busRouteID, "Name": list[iii].name });
            }
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.loadBusStopDataSource = function (tableView, list, dataSource) {

        for (iii = 0; iii < list.length; iii++) {
            dataSource.push({ "BusStopID": list[iii].busStopID, "Name": list[iii].name});
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.getIndexBusRouteID = function (list, busRouteID) {
        for (ii = 0; ii < list.length; ii++) {
            if (list[ii].busRouteID == busRouteID) {
                return ii;
            }
        }
        return -1;
    }

    this.getIndexBusStopID = function (list, busStopID) {
        for (ii = 0; ii < list.length; ii++) {
            if (list[ii].busStopID == busStopID) {
                return ii;
            }
        }
        return -1;
    }

    this.getIndexCompanyID = function (list, companyID) {
        for (ii = 0; ii < list.length; ii++) {
            if (list[ii].companyID == companyID) {
                return ii;
            }
        }
        return -1;
    }

    this.hideAllBusStopsChecked = function (list, objMapControl) {
        for (lk = 0; lk < list.length; lk++) {
            objMapControl.setVisibleMarker(list[lk].marker, false);
        }
    }

    this.showAllBusStopsChecked = function (list) {
        for (lk = 0; lk < list.length; lk++) {
            list[lk].marker.setVisible(list[lk].checked);
        }
    }

    this.clearSelection = function (tableView, list) {
        for (k = 0; k < list.length; k++) {
            list[k].checked = false;
            tableView.clearSelectedItems();
        }
    }

    this.enableDisableBusStopEventClickMap = function (opener, checked) {
        if (checked) {
            opener.objMapControl.clearListenerClic();
            opener.objMapControl.setVisibleMarker(opener.globalBusStopsManager.busStopMarker, true);
            opener.objMapControl.addListenerBusStopsMarkersClick();
        }
        else {
            opener.objMapControl.clearListenerClic();
            opener.objMapControl.setVisibleMarker(opener.globalBusStopsManager.busStopMarker, false);
            opener.objMapControl.setPositionMarker(opener.globalBusStopsManager.busStopMarker, null);
        }
    }

    this.isValidToInsertBusStop = function (opener, objects) {
        try {
            opener.objMapControl.getPositionMarker(opener.globalBusStopsManager.busStopMarker);
            objects.lat = stringToFloatForPosition(opener.objMapControl.getPositionXtoString(opener.objMapControl.getPositionMarker(opener.globalBusStopsManager.busStopMarker)));
            objects.lng = stringToFloatForPosition(opener.objMapControl.getPositionYtoString(opener.objMapControl.getPositionMarker(opener.globalBusStopsManager.busStopMarker)));
        }
        catch (e) {
            objWindowsMessageManager.show_Warning("No se ha ingresado el marcador de la parada de Bus.", titles.busStopsTitle);
            return false;
        }

        if (opener.globalBusStopsManager.companyID != -1) {
            if (opener.globalBusStopsManager.busRouteID != -1) {
                if (objects.busStopName != "") {
                    return true;
                }
                else {
                    objWindowsMessageManager.show_Warning("No se ha ingresado el nombre de la parada de Bus.", titles.busStopsTitle);
                    return false;
                }
            }
            else {
                objWindowsMessageManager.show_Warning("No se ha seleccionado la Ruta de Bus.", titles.busStopsTitle);
                return false;
            }
        }
        else {
            objWindowsMessageManager.show_Warning("No se ha seleccionado la compañia.", titles.busStopsTitle);
            return false;
        }
    }

    this.isValidToGetBusStop = function (opener, busRouteID, tableView) {

        this.clearSelection(tableView, opener.globalBusStopsManager.busStopsList);
        clearList(opener.globalBusStopsManager.busStopsList);
        clearDataSource(opener.globalBusStopsManager.busStopsDataSource, tableView, true);

        index = this.getIndexBusRouteID(opener.globalBusStopsManager.busRoutesList, busRouteID);

        if (index != -1) {
            opener.globalBusStopsManager.busRoutesList[index].checked = true;
            opener.globalBusStopsManager.busRouteID = busRouteID;
            return true;
        }
        else {
            return false;
        }
    }

    this.isValidToGetBusRoutes = function (opener, companyID, tableView) {

        this.clearSelection(tableView, opener.globalBusStopsManager.busRoutesList);
        clearList(opener.globalBusStopsManager.busRoutesList);
        clearDataSource(opener.globalBusStopsManager.busRoutesDataSource, tableView, true);
        index = this.getIndexCompanyID(opener.globalBusStopsManager.companiesList, companyID);

        if (index != -1) {
            opener.globalBusStopsManager.companiesList[index].checked = true;
            opener.globalBusStopsManager.companyID = companyID;
            return true;
        }
        else {
            return false;
        }

        return false;
    }

    this.busStopGridRowSelecting = function (opener, args, isZoom, isCenter) {
        var index = -1;
        var busStopID;
        try {
            if (args._domEvent.target.cellIndex != 0) {
                busStopID = args.getDataKeyValue("BusStopID");
                index = BusStopsManager.getIndexBusStopID(opener.globalBusStopsManager.busStopsList, busStopID);
                if (index != -1) {
                    opener.globalBusStopsManager.busStopsList[index].checked = true;
                    if (isCenter) {
                        opener.objMapControl.centerMap(opener.objMapControl.getPositionMarker(opener.globalBusStopsManager.busStopsList[index].marker));
                    }
                    
                    if (isZoom) {
                        opener.objMapControl.zoomMap(16);
                    }
                    BusStopsManager.showAllBusStopsChecked(opener.globalBusStopsManager.busStopsList);
                }
            }
            else {
                index = BusStopsManager.getIndexBusStopID(opener.globalBusStopsManager.busStopsList, args.getDataKeyValue("BusStopID"));
                if (index != -1) {
                    args.set_cancel(true);
                }
            }
        }
        catch (e) {
            null;
        }
    }

    this.busStopInsertSuccessful = function (opener, id, tree, busStopName) {
        var myBusStop = new BusStop();
        myBusStop.setBusStop(opener.objMapControl, id, busStopName, opener.objMapControl.getPositionXtoString(opener.objMapControl.getPositionMarker(opener.globalBusStopsManager.busStopMarker)), opener.objMapControl.getPositionYtoString(opener.objMapControl.getPositionMarker(opener.globalBusStopsManager.busStopMarker)));
        myBusStop.checked = true;
        opener.globalBusStopsManager.busStopsList.push(myBusStop);
        clearDataSource(opener.globalBusStopsManager.busStopsDataSource, tree, false);
        this.loadBusStopDataSource(tree, opener.globalBusStopsManager.busStopsList, opener.globalBusStopsManager.busStopsDataSource);
        this.showAllBusStopsChecked(opener.globalBusStopsManager.busStopsList);
        this.selectLastItemByBusStop(tree, opener.globalBusStopsManager.busStopsList);
        opener.objMapControl.setPositionMarker(opener.globalBusStopsManager.busStopMarker, null);
    }

    this.selectLastItemByBusStop = function (masterTable, list) {
        masterTable.selectItem(list.length - 1);
    }

    this.busStopGridOnRowClick = function (opener, args) {
        if (args._domEvent.target.cellIndex == 0) {// La columna 0 Representa la columna de eliminar
            var index = this.getIndexBusStopID(opener.globalBusStopsManager.busStopsList, args.getDataKeyValue("BusStopID"));
            if (index != -1) {
                if (confirm('¿Desea eliminar la parada de Bus?')) {
                    opener.globalBusStopsManager.busStopID = args.getDataKeyValue("BusStopID");
                    return true;
                }
            }
        }
        return false;
    }

    this.refreshAfterDeleteBusStop = function (opener, tree) {
        for (i = 0; i < opener.globalBusStopsManager.busStopsList.length; i++) {

            if (opener.globalBusStopsManager.busStopID == opener.globalBusStopsManager.busStopsList[i].busStopID) {
                opener.globalBusStopsManager.busStopsList[i].marker.setMap(null);
                opener.globalBusStopsManager.busStopsList.splice(i, 1);
            }
        }

        clearDataSource(opener.globalBusStopsManager.busStopsDataSource, tree, true);
        this.loadBusStopDataSource(tree, opener.globalBusStopsManager.busStopsList, opener.globalBusStopsManager.busStopsDataSource);
    }

}

function BusRoutesManager() {

    this.openXMLBusRoutesByCompanyID = function (xmlObject, list) {
        var xmlBusRoutes = jQuery.parseXML(xmlObject);

        var busRouteID;
        var name;

        var myBusRoute;

        jQuery(xmlBusRoutes).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                busRouteID = jQuery(this).find('BusRouteID').text();
                name = jQuery(this).find('Name').text();
                myBusRoute = new BusRoute();
                myBusRoute.setBusRoute(busRouteID, name);

                list.push(myBusRoute);
            });
        });
    }

    this.openXMLBusStopsByCompanyAndBusRouteID = function (objMapControl, xmlObject, globalObject) {
        var xmlBusStops = jQuery.parseXML(xmlObject);

        var busStopID;
        var name;
        var latitude;
        var longitude;

        var myBusStop;

        jQuery(xmlBusStops).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                busStopID = jQuery(this).find('BusStopID').text();
                name = jQuery(this).find('Name').text();
                latitude = jQuery(this).find('Latitude').text();
                longitude = jQuery(this).find('Longitude').text();
                myBusStop = new BusStop();
                myBusStop.setBusStop(objMapControl, busStopID, name, latitude, longitude, objMapControl);

                list.push(myBusStop);
            });
        });
    }

    this.openXMLBusRouteDetailsByBusRouteID = function (xmlObject, globalObject) {
        var xmlBusRoutes = jQuery.parseXML(xmlObject);

        var pos;
        var latitude;
        var longitude;

        globalObject.temporalyList = [];

        jQuery(xmlBusRoutes).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                pos = jQuery(this).find('Pos').text();
                latitude = jQuery(this).find('Latitude').text();
                longitude = jQuery(this).find('Longitude').text();
                
                globalObject.temporalyList.push(opener.objMapControl.addPosition(stringToFloatForPosition(latitude), stringToFloatForPosition(longitude)));
            });
        });
    }

    this.loadBusRoutesDataSource = function (tableView, list, dataSource) {

        if (dataSource.length == 0) {
            for (iii = 0; iii < list.length; iii++) {
                dataSource.push({ "BusRouteID": list[iii].busRouteID, "Name": list[iii].name });
            }
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.loadBusStopDataSource = function (tableView, list, dataSource) {

        for (iii = 0; iii < list.length; iii++) {
            dataSource.push({ "BusStopID": list[iii].busStopID, "Name": list[iii].name });
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.clearBusRoutes = function (opener){
        var length = opener.globalBusRoutesManager.polygonoBusRouteMarkers.length;
        opener.globalBusStopsManager.firstBusRoute = true;

            for (i = 0; i < length; i++) {
                opener.objMapControl.clearMarkerFromMap(opener.globalBusRoutesManager.polygonoBusRouteMarkers[length-1-i]);
                opener.globalBusRoutesManager.polygonoBusRouteMarkers.pop();
            }
        
            if (opener.globalBusRoutesManager.busRoutes.length > 0) {
            
                length = opener.globalBusRoutesManager.busRoutes[0].legs.length;
            
                for(i=0; i < length; i++){
                    opener.globalBusRoutesManager.busRoutes[0].legs.pop();
                }
            
                opener.globalBusRoutesManager.response.routes = opener.globalBusRoutesManager.busRoutes;
                opener.objMapControl.hideDirectionsDisplay(opener.globalBusRoutesManager.directionsDisplay);
            }
            opener.globalBusRoutesManager.isValidClickPoint = true;
    }

    this.getIndexBusRouteID = function (list, busRouteID) {
        for (ii = 0; ii < list.length; ii++) {
            if (list[ii].busRouteID == busRouteID) {
                return ii;
            }
        }
        return -1;
    }

    this.getIndexCompanyID = function (list, companyID) {
        for (ii = 0; ii < list.length; ii++) {
            if (list[ii].companyID == companyID) {
                return ii;
            }
        }
        return -1;
    }

    this.clearSelection = function (tableView, list) {
        for (k = 0; k < list.length; k++) {
            list[k].checked = false;
            tableView.clearSelectedItems();
        }
    }

    this.enableDisableBusRouteEventClickMap = function (opener, checked) {
        if (checked) {
            opener.objMapControl.clearListenerClic();
            opener.objMapControl.addListenerClickBusRoute();
        }
        else {
            opener.objMapControl.clearListenerClic();
        }
    }

    this.isValidToInsertBusRoute = function (opener, objects) {

        if (opener.globalBusRoutesManager.polygonoBusRouteMarkers.length > 1) {
            if (opener.globalBusRoutesManager.response != null) {
                if (opener.globalBusRoutesManager.response.routes.length > 0) {
                    if (opener.globalBusRoutesManager.response.routes[0].legs.length == opener.globalBusRoutesManager.polygonoBusRouteMarkers.length - 1) {
                        for (i = 0; i < opener.globalBusRoutesManager.polygonoBusRouteMarkers.length; i++) {
                            objects.latList.push(opener.objMapControl.getPositionXtoString(opener.objMapControl.getPositionMarker(opener.globalBusRoutesManager.polygonoBusRouteMarkers[i])));
                            objects.lngList.push(opener.objMapControl.getPositionYtoString(opener.objMapControl.getPositionMarker(opener.globalBusRoutesManager.polygonoBusRouteMarkers[i])));
                        }
                    }
                    else {
                        objWindowsMessageManager.show_Warning("No se ha registrado el detalle de la ruta en el mapa de forma correcta, existen puntos inválidos.", titles.busRoutesTitle);
                        return false;
                    }
                }
                else {
                    objWindowsMessageManager.show_Warning("No se ha registrado el detalle de la ruta en el mapa de forma correcta, existen puntos inválidos.", titles.busRoutesTitle);
                    return false;
                }
            }
            else {
                objWindowsMessageManager.show_Warning("No se ha registrado el detalle de la ruta en el mapa de forma correcta, existen puntos inválidos.", titles.busRoutesTitle);
                return false;
            }
        }
        else {
            objWindowsMessageManager.show_Warning("No se ha registrado el detalle de la ruta en el mapa, debe registrar almenos dos puntos válidos.", titles.busRoutesTitle);
            return false;
        }
        
        if (opener.globalBusRoutesManager.companyID != -1) {
            if (objects.busRouteName != "") {
                return true;
            }
            else {
                if (objects.isBtnBusRouteToSave) {
                    objWindowsMessageManager.show_Warning("No se ha ingresado el nombre de la ruta de Bus.", titles.busRoutesTitle);
                    return false;
                }
                else {
                    return true;
                }
            }
        }
        else {
            objWindowsMessageManager.show_Warning("No se ha seleccionado la compañia.", titles.busRoutesTitle);
            return false;
        }
    }

    this.busRouteInsertSuccessful = function (opener, busRouteID, tree, busRouteName) {
        myBusRoute = new BusRoute();
        myBusRoute.setBusRoute(busRouteID, busRouteName);
        myBusRoute.checked = true;
        opener.globalBusRoutesManager.busRoutesList.push(myBusRoute);
        clearDataSource(opener.globalBusRoutesManager.busRoutesDataSource, tree, false);
        this.loadBusRoutesDataSource(tree, opener.globalBusRoutesManager.busRoutesList, opener.globalBusRoutesManager.busRoutesDataSource);
        this.selectLastItemByBusRoute(tree, opener.globalBusRoutesManager.busRoutesList);
    }

    this.selectLastItemByBusRoute = function (masterTable, list) {
        masterTable.selectItem(list.length - 1);
    }

    this.isValidToGetBusRoutes = function (opener, companyID, tableView) {
        this.clearSelection(tableView, opener.globalBusRoutesManager.busRoutesList);
        clearList(opener.globalBusRoutesManager.busRoutesList);
        clearDataSource(opener.globalBusRoutesManager.busRoutesDataSource, tableView, true);
        index = this.getIndexCompanyID(opener.globalBusRoutesManager.companiesList, companyID);

        if (index != -1) {
            opener.globalBusRoutesManager.companiesList[index].checked = true;
            opener.globalBusRoutesManager.companyID = companyID;
            return true;
        }
        else {
            return false;
        }

        return false;
    }

    this.busRoutesGridRowSelecting = function (opener, busRouteID) {

        var index = -1;
        var busRouteID;
        try {
            index = this.getIndexBusRouteID(opener.globalBusRoutesManager.busRoutesList, busRouteID);
            if (index != -1) {
                opener.globalBusRoutesManager.busRoutesList[index].checked = true;
                opener.globalBusRoutesManager.busRouteID = busRouteID;
                return true;
            }
        }
        catch (e) {
            null;
            return false;
        }
    }

    this.busRoutesGridOnRowClick = function (opener, args) {
        if (args._domEvent.target.cellIndex == 0) {// La columna 0 Representa la columna de eliminar
            var index = this.getIndexBusRouteID(opener.globalBusRoutesManager.busRoutesList, args.getDataKeyValue("BusRouteID"));
            if (index != -1) {
                if (confirm('¿Desea eliminar la ruta de Bus?')) {
                    opener.globalBusRoutesManager.busRouteID = args.getDataKeyValue("BusRouteID");
                    return true;
                }
                else {
                    opener.globalBusRoutesManager.isSeletedItemBusRoute = false;
                }
            }
        }
        return false;
    }
}

function MasterPage() {
    this.openXMLTrackDataLastLocationImei = function (imeiSelected, objMapControl, xmlObject, list) {
        var xmlImei = jQuery.parseXML(xmlObject);
        var index;

        var imei;
        var latitude;
        var longitude;
        var lastMessageImei;
        //var geoferenceEnterAlarm;
        //var geoferenceExitAlarm;
        //var sosAlarm;
        var speed;
        var heading;

        var peopleIn;
        var peopleOut;
        var peopleInside;
        
        var myGPSNotification;
        var gpsNotificationList = [];
        var gpsImeiNotificationList = [];
        var gpsImei;
        var notificationText;

        var lastGpsImeiNotification;
        var currentGpsImeiNotification = "";

        jQuery(xmlImei).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                imei = jQuery(this).find('GPSImei').text();
                latitude = jQuery(this).find('Latitude').text();
                longitude = jQuery(this).find('Longitude').text();
                lastMessageImei = jQuery(this).find('LastMessageImei').text();
                peopleIn = jQuery(this).find('PeopleTotalIn').text();
                peopleOut = jQuery(this).find('PeopleTotalOut').text();
                peopleInside = jQuery(this).find('PeopleTotalInside').text();
                //geoferenceEnterAlarm = jQuery(this).find('GeoferenceEnterAlarm').text();
                //geoferenceExitAlarm = jQuery(this).find('GeoferenceExitAlarm').text();
                //sosAlarm = jQuery(this).find('SOSAlarm').text();
                speed = jQuery(this).find('Speed').text();
                try{
                    heading = parseInt(jQuery(this).find('Heading').text());
                }
                catch(ex){
                    heading = 0;
                }
                index = MasterPage.getIndexImei(list, imei);

                if (index != -1) {
                    list[index].updatePosition(imeiSelected, objMapControl, latitude, longitude, speed, heading, lastMessageImei, peopleIn, peopleOut, peopleInside);
                    //list[index].updateNotificationText();
                    //list[index].updateAlamsNotifications(geoferenceExitAlarm, geoferenceEnterAlarm, sosAlarm);
                }
            });
            jQuery(this).find('Table1').each(function () {

                gpsImei = jQuery(this).find('GPSImei').text();
                notificationText = jQuery(this).find('NotificationText').text();

                myGPSImeiNotification = new GPSImeiNotification();
                myGPSImeiNotification.setGPSImeiNotification(gpsImei, notificationText);               

                gpsNotificationList.push(myGPSImeiNotification);
            });
        });

        
        
        if (gpsNotificationList.length > 0) {

            lastGpsImeiNotification = gpsNotificationList[0].gpsImei;
            gpsImeiNotificationList = [];
            index = -1;

            for (i = 0; i < gpsNotificationList.length; i++) {

                if (lastGpsImeiNotification != gpsNotificationList[i].gpsImei) {
                    index = MasterPage.getIndexImei(list, lastGpsImeiNotification);
                    if (index != -1) {
                        list[index].updateNotificationText(gpsImeiNotificationList);
                        
                        gpsImeiNotificationList = [];
                        index = -1;
                    }
                }

                gpsImeiNotificationList.push(gpsNotificationList[i].notificationText);
                lastGpsImeiNotification = gpsNotificationList[i].gpsImei;
            }

            index = MasterPage.getIndexImei(list, lastGpsImeiNotification);
            if (index != -1) {
                list[index].updateNotificationText(gpsImeiNotificationList);
            }
        }
    }

    this.openXMLTrackDataLastLocationImeiRoutes = function (objMapControl, xmlObject, list, map) {
        var xmlImei = jQuery.parseXML(xmlObject);
        var index;

        var imei;
        var latitude;
        var longitude;
        //var lastMessageImei;
        //var geoferenceEnterAlarm;
        //var geoferenceExitAlarm;
        //var sosAlarm;
        var speed;

        //var peopleIn;
        //var peopleOut;
        //var peopleInside;

        //var myGPSNotification;
        //var gpsNotificationList = [];
        //var gpsImeiNotificationList = [];
        //var gpsImei;
        //var notificationText;

        //var lastGpsImeiNotification;
        //var currentGpsImeiNotification = "";

        jQuery(xmlImei).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                imei = jQuery(this).find('GPSImei').text();
                latitude = jQuery(this).find('Latitude').text();
                longitude = jQuery(this).find('Longitude').text();
                //lastMessageImei = jQuery(this).find('LastMessageImei').text();
                //peopleIn = jQuery(this).find('PeopleTotalIn').text();
                //peopleOut = jQuery(this).find('PeopleTotalOut').text();
                //peopleInside = jQuery(this).find('PeopleTotalInside').text();
                //geoferenceEnterAlarm = jQuery(this).find('GeoferenceEnterAlarm').text();
                //geoferenceExitAlarm = jQuery(this).find('GeoferenceExitAlarm').text();
                //sosAlarm = jQuery(this).find('SOSAlarm').text();
                speed = jQuery(this).find('Speed').text();

                index = MasterPage.getIndexImei(list, imei);
                
                if (index != -1) {
                    list[index].updateMinPosition(objMapControl, latitude, longitude, speed, map);
                    //list[index].updateNotificationText();
                    //list[index].updateAlamsNotifications(geoferenceExitAlarm, geoferenceEnterAlarm, sosAlarm);
                }
            });
            /*jQuery(this).find('Table1').each(function () {

                gpsImei = jQuery(this).find('GPSImei').text();
                notificationText = jQuery(this).find('NotificationText').text();

                myGPSImeiNotification = new GPSImeiNotification();
                myGPSImeiNotification.setGPSImeiNotification(gpsImei, notificationText);

                gpsNotificationList.push(myGPSImeiNotification);
            });*/
        });



        /*if (gpsNotificationList.length > 0) {

            lastGpsImeiNotification = gpsNotificationList[0].gpsImei;
            gpsImeiNotificationList = [];
            index = -1;

            for (i = 0; i < gpsNotificationList.length; i++) {

                if (lastGpsImeiNotification != gpsNotificationList[i].gpsImei) {
                    index = MasterPage.getIndexImei(list, lastGpsImeiNotification);
                    if (index != -1) {
                        list[index].updateNotificationText(gpsImeiNotificationList);

                        gpsImeiNotificationList = [];
                        index = -1;
                    }
                }

                gpsImeiNotificationList.push(gpsNotificationList[i].notificationText);
                lastGpsImeiNotification = gpsNotificationList[i].gpsImei;
            }

            index = MasterPage.getIndexImei(list, lastGpsImeiNotification);
            if (index != -1) {
                list[index].updateNotificationText(gpsImeiNotificationList);
            }
        }*/
    }

    this.getIndexImei = function (list, imei) {
        for (ii = 0; ii < list.length; ii++) {
            if (imei == list[ii].imei) {
                return ii;
            }
        }
        return -1;
    }

    this.openXMLCompanyInfo = function (xmlObject) {
        var xmlImei = jQuery.parseXML(xmlObject);
 
        jQuery(xmlImei).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                globalMasterPage.logoCompany = jQuery(this).find('Logo').text();
            });
        });            
    }

}

function Routes() {

    this.hideHistoryRoute = function (opener) {
        opener.objMapControl.hideHistoryRoute();
    }
    this.openCollectionStringTrackDataByImeiFirsSelection = function (stringCollection, opener) {

        this.hideHistoryRoute(opener);
        totalList = opener.globalList.trackDataByImei.length;
        for (k = 0; k < totalList; k++) {
            opener.globalList.trackDataByImei.pop();
        }
        //mycar.setPosition(null);
        opener.objMapControl.setPositionMarker(opener.objMapControl.GPSImeiRoute, null);

        //var xmlImei = jQuery.parseXML(xmlObject);

        var kmAnterior;
        var kmActual;
        var kmtotal;

        var imei;
        var hour;
        var latitude;
        var longitude;
        var speed;
        var imageLocation;

        var myTrackData;
        var myLastTrackData = null;

        var peopleIn;
        var peopleOut;
        var peopleTotalInside;
        var peopleTotalIn;
        var peopleTotalOut;

        var info = [];

        for (i = 0; i < stringCollection.length; i++) {

            info = [];

            info = stringCollection[i].split('&');

            if (i == 0) {
                imei = info[0];
                imageLocation = info[1];
            }
            else {
                hour = info[0];
                speed = info[1];
                latitude = info[2];
                longitude = info[3];
                peopleIn = info[4];
                peopleOut = info[5];
                peopleInside = info[6];
                peopleTotalIn = info[7];
                peopleTotalOut = info[8];

                myTrackData = new TrackData();

                kmAnterior = 0;
                kmActual = 0;
                kmtotal = 0;

                myTrackData.setTrackData(opener.objMapControl, imei, speed, latitude, longitude, imageLocation, hour, peopleIn, peopleOut, peopleTotalInside, peopleTotalIn, peopleTotalOut);

                if (myLastTrackData != null) {
                    kmAnterior = myLastTrackData.currentKm;
                    kmActual = opener.objMapControl.getDistanceKms(myLastTrackData.position, myTrackData.position);

                    kmtotal = parseFloat(kmAnterior) + parseFloat(kmActual);
                    myTrackData.currentKm = kmtotal;
                }
                else {
                    myTrackData.currentKm = 0;
                }

                opener.globalList.trackDataByImei.push(myTrackData);
                myLastTrackData = myTrackData;
            }
        }
    }
    this.openCollectionStringTrackDataByImeiSecondSelection = function (stringCollection, opener) {

        var kmAnterior;
        var kmActual;
        var kmtotal;

        var imei;
        var hour;
        var latitude;
        var longitude;
        var speed;
        var imageLocation;

        var myTrackData;
        var myLastTrackData = opener.globalList.trackDataByImei[opener.globalList.trackDataByImei.length - 1];
        
        var peopleIn;
        var peopleOut;
        var peopleTotalInside;
        var peopleTotalIn;
        var peopleTotalOut;

        var info = [];

        for (i = 1; i < stringCollection.length; i++) {

            info = [];

            info = stringCollection[i].split('&');

            hour = info[0];
            speed = info[1];
            latitude = info[2];
            longitude = info[3];
            peopleIn = info[4];
            peopleOut = info[5];
            peopleTotalInside = info[6];
            peopleTotalIn = info[7];
            peopleTotalOut = info[8];

            myTrackData = new TrackData();

            kmAnterior = 0;
            kmActual = 0;
            kmtotal = 0;

            myTrackData.setTrackData(opener.objMapControl, imei, speed, latitude, longitude, imageLocation, hour, peopleIn, peopleOut, peopleTotalInside, peopleTotalIn, peopleTotalOut);

            if (myLastTrackData != null) {
                kmAnterior = myLastTrackData.currentKm;
                kmActual = opener.objMapControl.getDistanceKms(myLastTrackData.position, myTrackData.position);

                kmtotal = parseFloat(kmAnterior) + parseFloat(kmActual);
                myTrackData.currentKm = kmtotal;
            }
            else {
                myTrackData.currentKm = 0;
            }

            opener.globalList.trackDataByImei.push(myTrackData);
            myLastTrackData = myTrackData;
        }
    }

    this.showStopsMarkers = function (opener) {
        for (i = 0; i < opener.globalList.stopsMarkers.length; i++) {
            opener.objMapControl.setVisibleMarker(opener.globalList.stopsMarkers[i].stopMarker, true);
        }
    }

    this.hideStopsMarkers = function (opener) {
        for (i = 0; i < opener.globalList.stopsMarkers.length; i++) {
            opener.objMapControl.setVisibleMarker(opener.globalList.stopsMarkers[i].stopMarker, false);
        }
    }

    this.enableDisableSliderRoute = function (toEnable, slider) {
        try {
            //var slider = getSliderRouter();
            slider.set_enabled(toEnable);
            slider.repaint();
        }
        catch (e) {

        }
    }

    this.isValidToLoadRoute = function (imei, date) {
        
        if (imei == -1) {
            objWindowsMessageManager.show_Warning('Debe seleccionar un dispositivo para cargar la ruta.', titles.RoutesHistoryTitle);
            return false;
        }
        else {

            if (date == "" || date == "//") {
                objWindowsMessageManager.show_Warning('Debe seleccionar una fecha para cargar la ruta.', titles.RoutesHistoryTitle);
                return false;
            }
            else {

                if (!isDate(date)) {
                    objWindowsMessageManager.show_Warning('Debe seleccionar una fecha válida para cargar la ruta.', titles.RoutesHistoryTitle);
                    return false;
                }

                return true;
            }
        }
    }

    this.changeDirectionPosition = function (opener, initialPosition, finalPosition) {
        var NS = ''; //(-)
        var OE = ''; //(|)
        if (stringToFloatForPosition(opener.objMapControl.getPositionXtoString(finalPosition)) < stringToFloatForPosition(opener.objMapControl.getPositionXtoString(initialPosition))) { NS = 'N'; }
        if (stringToFloatForPosition(opener.objMapControl.getPositionXtoString(finalPosition)) > stringToFloatForPosition(opener.objMapControl.getPositionXtoString(initialPosition))) { NS = 'S'; }
        if (stringToFloatForPosition(opener.objMapControl.getPositionYtoString(finalPosition)) > stringToFloatForPosition(opener.objMapControl.getPositionYtoString(initialPosition))) { OE = 'E'; }
        if (stringToFloatForPosition(opener.objMapControl.getPositionYtoString(finalPosition)) < stringToFloatForPosition(opener.objMapControl.getPositionYtoString(initialPosition))) { OE = 'O'; }

        var direction = NS + OE;
        if (opener.globalRoutes.lastCardinalPoint != "") {
            if (opener.globalRoutes.lastCardinalPoint != direction) {
                if ((opener.globalRoutes.lastCardinalPoint == "NO" && direction == "SE") || (opener.globalRoutes.lastCardinalPoint == "SE" && direction == "NO") || (opener.globalRoutes.lastCardinalPoint == "NE" && direction == "SO") || (opener.globalRoutes.lastCardinalPoint == "SO" && direction == "NE") || (opener.globalRoutes.lastCardinalPoint == "NE" && direction == "NO") || (opener.globalRoutes.lastCardinalPoint == "NO" && direction == "NE") || (opener.globalRoutes.lastCardinalPoint == "NO" && direction == "SO") || (opener.globalRoutes.lastCardinalPoint == "SO" && direction == "NO") || (opener.globalRoutes.lastCardinalPoint == "NE" && direction == "SE") || (opener.globalRoutes.lastCardinalPoint == "SE" && direction == "NE"))
                {
                    opener.globalRoutes.lastCardinalPoint = direction;
                    return true;
                }
            }
        }
        opener.globalRoutes.lastCardinalPoint = direction;
        return false;
    }

    this.getIndexImei = function (list, imei) {
        for (ii = 0; ii < list.length; ii++) {
            if (imei == list[ii].imei) {
                return ii;
            }
        }
        return -1;
    }

    this.showHistoryRoute = function(opener) {
        opener.objMapControl.showHistoryRoute();
    };
}

function RoutesManager()
{

    this.openXMLUsersByUserGroupID = function (xmlObject, list) {
        var xmlUsers = jQuery.parseXML(xmlObject);

        var username;
        var name;
        var firstName;
        var lastName;

        var myUser;

        jQuery(xmlUsers).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                username = jQuery(this).find('Username').text();
                name = jQuery(this).find('Name').text();
                firstName = jQuery(this).find('FirstName').text();
                lastName = jQuery(this).find('LastName').text();

                myUser = new User();
                myUser.setUser(username, name, firstName, lastName);

                list.push(myUser);
            });
        });
    }

    this.loadUsersRouteByUserGroupIDDataSource = function (tableView, dataSource, list) {

        clearDataSource(dataSource, tableView, true);
        for (iii = 0; iii < list.length; iii++) {
            dataSource.push({ "Username": list[iii].username, "Name": list[iii].name, "FirstName": list[iii].firstName, "LastName": list[iii].lastName });
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.openXMLImeiByUser = function (xmlObject, list) {
        var xmlImei = jQuery.parseXML(xmlObject);

        var gpsImei;
        var name;
        var image;
        var latitude;
        var longitude;

        var myGPSStock;

        jQuery(xmlImei).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                gpsImei = jQuery(this).find('GPSImei').text();
                name = jQuery(this).find('Name').text();
                image = jQuery(this).find('Image').text();
                latitude = jQuery(this).find('Latitude').text();
                longitude = jQuery(this).find('Longitude').text();

                myGPSStock = new GPSStock();
                myGPSStock.setGPSImei(opener.objMapControl, gpsImei, name, image, latitude, longitude);

                list.push(myGPSStock);
            });
        });


    }

    this.loadImeiDataSource = function (tableView, dataSource, list) {

        clearDataSource(dataSource, tableView, true);

        for (iii = 0; iii < list.length; iii++) {
            dataSource.push({ "GPSImei": list[iii].gpsImei, "Name": list[iii].name });
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.openXMLDepartmentsByCompanyID = function (xmlObject, list) {
        var xmlDepartments = jQuery.parseXML(xmlObject);

        var departmentID;
        var name;

        var myDepartment;

        clearList(list);

        jQuery(xmlDepartments).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                departmentID = jQuery(this).find('DepartmentID').text();
                name = jQuery(this).find('Name').text();

                myDepartment = new Department();
                myDepartment.setDepartment(departmentID, name);

                list.push(myDepartment);
            });
        });
    }

    this.loadDepartmentsDataSource = function (tableView, dataSource, list) {

        clearDataSource(dataSource, tableView, true);
        
        for (iii = 0; iii < list.length; iii++) {
            dataSource.push({ "DepartmentID": list[iii].departmentID, "Name": list[iii].name });
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.getIndexDepartmentID = function (list, departmentID) {
        for (ii = 0; ii < list.length; ii++) {
            if (list[ii].departmentID == departmentID) {
                return ii;
            }
        }
        return -1;
    }

    this.getIndexUserGroupID = function (list, userGroupID) {
        for (ii = 0; ii < list.length; ii++) {
            if (list[ii].userGroupID == userGroupID) {
                return ii;
            }
        }
        return -1;
    }

    this.getIndexClientID = function (list, clientID) {
        for (ii = 0; ii < list.length; ii++) {
            if (list[ii].clientID == clientID) {
                return ii;
            }
        }
        return -1;
    }

    this.openXMLUsersGroupsByDepartmentID = function (xmlObject, list) {
        var xmlUsersGroups = jQuery.parseXML(xmlObject);

        var userGroupID;
        var name;

        var myUserGroup;

        clearList(list);

        jQuery(xmlUsersGroups).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                userGroupID = jQuery(this).find('UserGroupID').text();
                name = jQuery(this).find('Name').text();

                myUserGroup = new UserGroup();
                myUserGroup.setUserGroup(userGroupID, name);

                list.push(myUserGroup);
            });
        });
    }

    this.loadUsersGroupsDataSource = function (tableView, dataSource, list) {

        clearDataSource(dataSource, tableView, true);

        for (iii = 0; iii < list.length; iii++) {
            dataSource.push({ "UserGroupID": list[iii].userGroupID, "Name": list[iii].name });
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.openXMLAllClientsByCompanyID = function (xmlObject, list, objMapControl) {
        var xmlClient = jQuery.parseXML(xmlObject);

        var clientID;
        var clientName;
        var clientGroupID;
        var clientGroupName;
        var latitude;
        var longitude;

        var myClient;

        clearList(list);

        jQuery(xmlClient).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                clientID = jQuery(this).find('ClientID').text();
                clientName = jQuery(this).find('ClientName').text();
                clientGroupID = jQuery(this).find('ClientGroupID').text();
                clientGroupName = jQuery(this).find('ClientGroupName').text();
                latitude = jQuery(this).find('Latitude').text();
                longitude = jQuery(this).find('Longitude').text();

                myClient = new Client();
                myClient.setClient(objMapControl, clientID, clientName, latitude, longitude);
                myClient.setClientGroup(clientGroupID, clientGroupName);
                myClient.checked = false;

                list.push(myClient);
            });
        });
    }

    this.loadAllGroupClientsByCompanyIDDataSource = function (tableView, list, dataSource, opener) {

        clearDataSource(dataSource, tableView, true);
        var lastGroupID = -1;
        for (iii = 0; iii < list.length; iii++) {

            if (lastGroupID != list[iii].clientGroupID) {
                dataSource.push({ "ClientGroupID": list[iii].clientGroupID, "ClientGroupName": list[iii].clientGroupName });
                //opener.objMapControl.setVisibleMarker(list[iii].marker, false);
                //opener.objMapControl.hideClientsRoutes();
            }

            lastGroupID = list[iii].clientGroupID;
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.loadAllClientsByCompanyIDDataSource = function (tableView, list, dataSource, opener) {

        clearDataSource(dataSource, tableView, true);

        for (iii = 0; iii < list.length; iii++) {
            if (!list[iii].checked && list[iii].visible) {
                dataSource.push({ "ClientID": list[iii].clientID, "ClientName": list[iii].clientName, "ClientGroupName": list[iii].clientGroupName });
                opener.objMapControl.setVisibleMarker(list[iii].marker, false);
                opener.objMapControl.hideClientsRoutes();
            }
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.loadAllClientsSelectedDataSource = function (tableView, list, dataSource, opener) {

        clearDataSource(dataSource, tableView, true);

        for (iii = 0; iii < list.length; iii++) {
            if (list[iii].checked) {
                opener.objMapControl.setVisibleMarker(list[iii].marker, true);
                dataSource.push({ "ClientID": list[iii].clientID, "NumPos": list[iii].numPos, "ClientName": list[iii].clientName, "ClientGroupName": list[iii].clientGroupName });
            }
        }
        tableView.clearSelectedItems();
        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.clientGroupsRoutesGridRowSelection = function (list, clientGroupID) {
        for (iii = 0; iii < list.length; iii++) {

            if (list[iii].clientGroupID == clientGroupID) {
                list[iii].visible = true;
            }

        }
    }

    this.clientGroupsRoutesGridRowDeselecting = function (list, clientGroupID) {
        for (iii = 0; iii < list.length; iii++) {

            if (list[iii].clientGroupID == clientGroupID) {
                list[iii].visible = false;
            }

        }
    }

    this.clientsRoutesGridRowSelection = function (args, opener) {
        var index = this.getIndexClientID(opener.globalRoutesManager.allClientsList, args.getDataKeyValue("ClientID"));
        if (index != -1) {
            opener.globalRoutesManager.allClientsList[index].checked = true;
            opener.objMapControl.setVisibleMarker(opener.globalRoutesManager.allClientsList[index].marker, true);
            opener.objMapControl.setTitleMarker(opener.globalRoutesManager.allClientsList[index].marker, opener.globalRoutesManager.allClientsList[index].clientName);
            opener.objMapControl.setCenterMap(opener.globalRoutesManager.allClientsList[index].position);
        }
    }

    this.clientsRoutesGridRowDeselecting = function (args, opener) {
        if (!opener.globalRoutes.isClear) {
            var index = this.getIndexClientID(opener.globalRoutesManager.allClientsList, args.getDataKeyValue("ClientID"));
            if (index != -1) {
                opener.globalRoutesManager.allClientsList[index].checked = false;
                opener.objMapControl.setVisibleMarker(opener.globalRoutesManager.allClientsList[index].marker, false);
            }
        }
    }

    this.clearNumPosClients = function (opener) {
        for (cont = 0; cont < opener.globalRoutesManager.allClientsList.length; cont++) {
            opener.globalRoutesManager.allClientsList[cont].numPos = null;
        }
    }

    this.getCantClientSelected = function (opener) {
        var cantClientSelected = 0;
        for (cont = 0; cont < opener.globalRoutesManager.allClientsList.length; cont++) {
            if (opener.globalRoutesManager.allClientsList[cont].checked) {
                cantClientSelected++;
            }
        }
        return cantClientSelected;
    }

    this.clearKmsAndDurationClients = function(opener, clearAll) {
        for (cont = 0; cont < opener.globalRoutesManager.allClientsList.length; cont++) {
            if (opener.globalRoutesManager.allClientsList[cont].numPos == null || clearAll) {
                opener.globalRoutesManager.allClientsList[cont].kms = null;
                opener.globalRoutesManager.allClientsList[cont].kmsText = null;
                opener.globalRoutesManager.allClientsList[cont].duration = null;
                opener.globalRoutesManager.allClientsList[cont].durationText = null;
                //opener.objMapControl.setVisibleMarker(opener.globalRoutesManager.allClientsList[cont].marker, false);
                //opener.objMapControl.setPositionMarker(opener.globalRoutesManager.allClientsList[cont].marker, null);
                //opener.objMapControl.setIconMarker(opener.globalRoutesManager.allClientsList[cont].marker, null);
                //opener.objMapControl.setVisibleMarker(opener.globalRoutesManager.allClientsList[cont].marker, false);
            }
        }
    }

    this.clearClientsMarkers = function (opener)
    {
        for (cont = 0; cont < opener.globalRoutesManager.allClientsList.length; cont++) {
            opener.objMapControl.setPositionMarker(opener.globalRoutesManager.allClientsList[cont].marker, null);
            //opener.objMapControl.setIconMarker(opener.globalRoutesManager.allClientsList[cont].marker, null);
            opener.objMapControl.setVisibleMarker(opener.globalRoutesManager.allClientsList[cont].marker, false);
        }
    }

    /*this.nextPositionIndexRoutetoDraw = function(opener) {
        for (opener.globalRoutes.currentIndexRoute = 0; opener.globalRoutes.currentIndexRoute < opener.globalRoutesManager.allClientsList.length; opener.globalRoutes.currentIndexRoute++) {
            if (opener.globalRoutesManager.allClientsList[opener.globalRoutes.currentIndexRoute].numPos == opener.globalRoutes.numPos) {
                opener.globalRoutes.numPos++;
                return true;
            }
        }
        return false;
    }*/

}

function GeoFences() {

    this.openXMLGeoFenceDetailsByGeoFenceID = function (opener, xmlObject, tree) {
        var xmlGeoFence = jQuery.parseXML(xmlObject);

        var geoFenceID;
        var name;
        var numPosList = [];
        var latitudeList = [];
        var longitudeList = [];

        var myGeoFence = new GeoFence();
        //var myGeoFenceInfo = new GeoFenceInfo();

        jQuery(xmlGeoFence).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                geoFenceID = jQuery(this).find('GeoFenceID').text();
                name = jQuery(this).find('Name').text();
                numPosList.push(jQuery(this).find('NumPos').text());
                latitudeList.push(jQuery(this).find('Latitude').text());
                longitudeList.push(jQuery(this).find('Longitude').text());
            });
        });

        myGeoFence.setGeoFence(geoFenceID, name, numPosList, latitudeList, longitudeList, opener);
        //myGeoFence.show = true;
        myGeoFence.checked = true;
        opener.globalGeoFences.geoFencesList.push(myGeoFence);

        //myGeoFenceInfo.setGeoFenceInfo(geoFenceID, description, imei);
        //gGeoFenceInfoList.push(myGeoFenceInfo);
        opener.objMapControl.clearGeoFenceMarkers(false);
        this.addRowClientDataSource(opener, opener.globalGeoFences.geoFencesList.length - 1, tree);
        //this.loadGeoFenceDataSource(opener.globalGeoFences.geoFencesDataSource, opener.globalGeoFences.geoFencesList, tree);
        //this.geoFence_ShowAllGeoFenceIDChecked(opener);
        //meg_addAndSelectGeoFenceComboBox(myGeoFence);
    }

    this.openXMLGeoFenceDetails = function (opener, xmlObject, list) {
        var xmlGeoFenceDetails = jQuery.parseXML(xmlObject);

        var geoFenceID;
        var name;
        var numPosList = [];
        var latitudeList = [];
        var longitudeList = [];

        var LastGeoFenceID = "";

        var myGeoFence;

        jQuery(xmlGeoFenceDetails).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                geoFenceID = jQuery(this).find('GeoFenceID').text();
                name = jQuery(this).find('Name').text();

                if (geoFenceID != LastGeoFenceID) {

                    if (LastGeoFenceID != "") {
                        list.push(myGeoFence);
                    }

                    myGeoFence = new GeoFence();

                    numPosList = [];
                    latitudeList = [];
                    longitudeList = [];

                    numPosList.push(jQuery(this).find('NumPos').text());
                    latitudeList.push(jQuery(this).find('Latitude').text());
                    longitudeList.push(jQuery(this).find('Longitude').text());

                    myGeoFence.setGeoFence(geoFenceID, name, numPosList, latitudeList, longitudeList, opener);
                }
                else {
                    numPosList.push(jQuery(this).find('NumPos').text());
                    latitudeList.push(jQuery(this).find('Latitude').text());
                    longitudeList.push(jQuery(this).find('Longitude').text());

                    myGeoFence.numPosList = numPosList;
                    myGeoFence.latitudeList = latitudeList;
                    myGeoFence.longitudeList = longitudeList;
                }

                LastGeoFenceID = geoFenceID;
            });
        });

        if (LastGeoFenceID != "") {
            list.push(myGeoFence);
        }

        //meg_addAndSelectGeoFenceComboBox(myGeoFence);
    }

    this.addRowClientDataSource = function(opener, index, tableView) {

        opener.globalGeoFences.geoFencesDataSource.push({ "GeoFenceID": opener.globalGeoFences.geoFencesList[index].geoFenceID, "Name": opener.globalGeoFences.geoFencesList[index].name });

        tableView.set_dataSource(opener.globalGeoFences.geoFencesDataSource);
        tableView.dataBind();
    }

    this.loadGeoFenceDataSource = function (dataSource, list, tableView) {

        clearDataSource(dataSource, tableView, true);

        for (iii = 0; iii < list.length; iii++) {
            dataSource.push({ "GeoFenceID": list[iii].geoFenceID, "Name": list[iii].name });
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.selectLastItemByImei = function(opener, masterTable) {
        masterTable.selectItem(opener.globalGeoFences.geoFencesList.length - 1);
        opener.globalGeoFences.geoFencesList[opener.globalGeoFences.geoFencesList.length - 1].showGeoFence(opener);
    }

    this.isValidToGetGeoFences = function (tableView, oldCompanyID, companyID, geoFencelist, companyList, dataSource) {
        //if (oldCompanyID != companyID) {

            this.clearSelection(tableView, geoFencelist);
            clearList(geoFencelist);
            clearDataSource(dataSource, tableView, true);

            index = this.getIndexCompanyID(companyList, companyID);

            if (index != -1) {
                companyList[index].checked = true;
                oldCompanyID = companyID;
                return true;
            }
            else{
                return false;
            }
        //}

        //return false;
    }



    this.clearSelection = function (tableView, list) {
        for (k = 0; k < list.length; k++) {
            list[k].checked = false;
            tableView.clearSelectedItems();
        }
    }

    this.getIndexCompanyID = function (list, companyID) {
        for (ii = 0; ii < list.length; ii++) {
            if (list[ii].companyID == companyID) {
                return ii;
            }
        }
        return -1;
    }

    this.getIndexGeoFenceID = function (list, geoFenceID) {
        for (ii = 0; ii < list.length; ii++) {
            if (list[ii].geoFenceID == geoFenceID) {
                return ii;
            }
        }
        return -1;
    }

    this.isValidToInsert = function (opener, polygonoName) {
        if (opener.globalGeoFences.companyID != -1) {
            if (polygonoName != "") {
                opener.globalGeoFences.latitudePolygonoList = []; //X
                opener.globalGeoFences.longitudePolygonoList = []; //Y

                if (opener.objMapControl.polygonoMarkers.length > 2) {
                    for (i = 0; i < opener.objMapControl.polygonoMarkers.length; i++) {
                        opener.globalGeoFences.latitudePolygonoList.push(opener.objMapControl.getPositionXtoString(opener.objMapControl.getPositionMarker(opener.objMapControl.polygonoMarkers[i])));
                        opener.globalGeoFences.longitudePolygonoList.push(opener.objMapControl.getPositionYtoString(opener.objMapControl.getPositionMarker(opener.objMapControl.polygonoMarkers[i])));
                    }
                    return true;

                } else {
                    objWindowsMessageManager.show_Info("Debe existir mínimo tres marcadores para crear un polígono.", titles.polygonoTitle);
                    return false;
                }
            }
            else {
                objWindowsMessageManager.show_Warning("Debe registrar un nombre para guardar el polígono.", titles.polygonoTitle);
                return false;
            }
        }
        else {
            objWindowsMessageManager.show_Warning("Debe seleccionar una compañía antes de guardar el polígono.", titles.polygonoTitle);
            return false;
        }
    }

    this.openXMLAndUpdateGeoFenceDetailsByGeoFenceID = function (xmlObject) {
        var xmlGeoFenceDetails = jQuery.parseXML(xmlObject);

        var geoFenceID;
        var description;
        var imei;
        var numPosList = [];
        var latitudeList = [];
        var longitudeList = [];

        jQuery(xmlGeoFenceDetails).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                geoFenceID = jQuery(this).find('GeoFenceID').text();
                description = jQuery(this).find('Description').text();
                imei = jQuery(this).find('Imei').text();

                numPosList.push(jQuery(this).find('NumPos').text());
                latitudeList.push(jQuery(this).find('Latitude').text());
                longitudeList.push(jQuery(this).find('Longitude').text());
            });
        });

        for (ii = 0; ii < globalList.geoFence.length; ii++) {
            if (geoFenceID == globalList.geoFence[ii].geoFenceID) {
                globalList.geoFence[ii].hideGeoFence();
                globalList.geoFence[ii].updateGeoFence(geoFenceID, description, imei, numPosList, latitudeList, longitudeList);

            }
        }

        /*for (ii = 0; ii < gGeoFenceInfoList.length; ii++) {
            if (geoFenceID == gGeoFenceInfoList[ii].geoFenceID) {
                gGeoFenceInfoList[ii].description = description;
                //meg_refreshGeoFenceInfoBomboBox();
            }
        }*/
    }
}

function NotificationHistory() {
    this.openXMLNotificationTrackData = function (xmlObject, list) {
        var xmlNotification = jQuery.parseXML(xmlObject);

        var gpsImei;
        var name;
        var notificationID;
        var datetime;
        var notificationText;

        var myNotificationsTrackData;

        jQuery(xmlNotification).find('NewDataSet').each(function () {
            jQuery(this).find('Table').each(function () {

                gpsImei = jQuery(this).find('GPSImei').text();
                name = jQuery(this).find('GPSName').text();
                notificationID = jQuery(this).find('NotificationID').text();
                datetime = jQuery(this).find('Datetime').text();
                notificationText = jQuery(this).find('NotificationText').text();

                myNotificationsTrackData = new NotificationsTrackData();
                myNotificationsTrackData.setNotificationTrackData(gpsImei, name, notificationID, datetime, notificationText);

                list.push(myNotificationsTrackData);
            });
        });
    }

    this.loadNotificationTrackDataDataSource = function (tableView, list, dataSource) {

        clearDataSource(dataSource, tableView, true);
        for (iii = 0; iii < list.length; iii++) {
            dataSource.push({ "GPSImei": list[iii].gpsImei, "GPSName": list[iii].name, "NotificationID": list[iii].notificationID, "Datetime": list[iii].datetime, "NotificationText": list[iii].notificationText});
        }

        tableView.set_dataSource(dataSource);
        tableView.dataBind();
    }

    this.isValidToGetNotifications = function (opener, beginDate, endDate)
    {
        if (opener.globalGPSImei.imeiSelected == -1) {
            objWindowsMessageManager.show_Warning('Debe seleccionar un GPS para consultar las notificaciones.', titles.notifications);
            return false;
        }
        else {

            if (beginDate == "" || beginDate == "//") {
                objWindowsMessageManager.show_Warning('Debe seleccionar la fecha desde para consultar las notificaciones.', titles.notifications);
                return false;
            }
            else {
                if (!isDate(beginDate)) {
                    objWindowsMessageManager.show_Warning('Debe seleccionar la fecha desde válida para consultar las notificaciones.', titles.notifications);
                    return false;
                }
                else {
                    if (endDate == "" || endDate == "//") {
                        objWindowsMessageManager.show_Warning('Debe seleccionar la fecha hasta para consultar las notificaciones.', titles.notifications);
                        return false;
                    }
                    else {
                        if (!isDate(endDate)) {
                            objWindowsMessageManager.show_Warning('Debe seleccionar la fecha hasta válida para consultar las notificaciones.', titles.notifications);
                            return false;
                        }
                        else {
                            if (getFormatDate(endDate) < getFormatDate(beginDate)) {
                                objWindowsMessageManager.show_Warning('La fecha Hasta no puede ser mayor a la fecha Desde.', titles.notifications);
                                return false;
                            }
                            return true;
                        }
                    }
                }
            }
        }
    }
}

//End Objects

//Begin Utilities...

function configDecimalSeparator(str) {
    return str;//.replace(".",",");
}

function stringToFloatForPosition(str) {
    return parseFloat(str.replace(",", "."));
}

function formatTwoDecimals(pmonto) {
    var val = parseFloat(pmonto);
    if (isNaN(val)) { return "0.00"; }
    if (val <= 0) { return "0.00"; }
    val += "";
    // Next two lines remove anything beyond 2 decimal places 
    if (val.indexOf('.') == -1) { return val + ".00"; }
    else { val = val.substring(0, val.indexOf('.') + 3); }
    val = (val == Math.floor(val)) ? val + '.00' : ((val * 10 == Math.floor(val * 10)) ? val + '0' : val);
    return val;
}

function getFormatDate (date) {
    var day = date.substring(0, 2);
    var month = date.substring(3, 5);
    var year = date.substring(6, 10);

    return year + '/' + month + '/' + day;
}

function leftpad(n, length) {
    n = n.toString();
    while (n.length < length) n = "0" + n;
    return n;
}

function isDate (date) {
    try {
        var newDate = new Date(date);
        return true;
    } catch (e) {
        return false;
    }
}

function clearList(list) {

    var length = list.length;

    for (iii = 0; iii < length; iii++) {
        list.pop();
    }

}

function clearDataSource(dataSource, tableView, clearSelectedItem) {
    var length = dataSource.length;
    for (i = 0; i < length; i++) {
        dataSource.pop();
    }

    if (clearSelectedItem) {
        tableView.clearSelectedItems();
    }

    tableView.set_dataSource(dataSource);
    tableView.dataBind();
}

function getIndexGpsImei(list, gpsImei) {
    for (ii = 0; ii < list.length; ii++) {
        if (list[ii].gpsImei == gpsImei) {
            return ii;
        }
    }
    return -1;
}

//End Utilities...

var titles = {
    polygonoTitle: "Polígonos",
    clientTitle: "Clientes",
    busStopsTitle: "Administrador de Paradas",
    busRoutesTitle: "Administrador de Rutas de Bus",
    RoutesHistoryTitle: "Rutas Históricas",
    routesAdministrator: "Administrador de Rutas",
    notifications: "Notificaciones"
};

var images = {
    location: "../../Template/Icons/GPSType/",
    locationStop: "../../Template/Icons/32px/stop.png",
    locationClient: "../../Template/Icons/32px/client.png",
    locationBusStop: "../../Template/Icons/48px/Bus-Stop.png",
    locationBusRoute: "../../Template/Icons/48px/Location_marker_pin_map_gps.png",
    locationPeopleCounter: "../../Template/Icons/32px/Group-Folder-icon.png",
};


/*
function InitializeObjects(page) {
    switch (page) {
        case "ClientManager.aspx":
            globalClientManager.clientMarker = objMapControl.addMarker(null, null, null);
            break;
        case "Routes.aspx":
            objMapControl.initializeRoutesObjects();
            break;
        case "GeoFences.aspx":
            objMapControl.initializeGeoFencesObjects();
            break;
        case "RoutesManager.aspx":
            objMapControl.initializeRoutesManagerObject();
            break;
        case "BusStopsManager.aspx":
            objMapControl.initializeBusStopsManagerObject();
            globalBusStopsManager.busStopMarker = objMapControl.addMarker(null, null, null);
            break;
        case "BusStopsRouteHistory.aspx":
            objMapControl.initializeBusStopsHistoryObject();
            break;
        case "BusStopsShowMultiplePages.aspx":
            objMapControl.initializeBusStopsHistoryObject();
            break;
        case "ClientsRouteHistory.aspx":
            objMapControl.initializeClientsHistoryObject();
            break;
        case "GenerateScripts.aspx":
            objMapControl.initializeForScripts();
            break;
        default:
            break;

    }
}

function ClearObjects(page) {

    var n = page.indexOf("NotificationManager.aspx");
    if (n > 0) {
        for (i = 0; i < globalNotificationManager.geoFencesList.length; i++) {
            //globalNotificationManager.geoFencesList[i].hideGeoFence(globalNotificationManager);
            objMapControl.clearPolygono(globalNotificationManager.geoFencesList[i].polygono);
        }
    }
}
*/